1

If I want to dynamically set an element as a new itemscope and give it an itemtype, what would itemscope be from a jQuery point of view? In other words, should I use .attr("itemscope", "") or .prop("itemscope", true)?

As an example, let's say I want to add an itemscope to my body tag and give it the type WebPage:

<body itemscope itemtype="http://schema.org/WebPage">

I can use $("body").attr("itemtype", "http://schema.org/WebPage") for the type, but what about the itemscope?

The thing is, when I use .prop('itemscope', true) I don't see these changes reflected in HTML (i.e. there's no visible change in the DOM), whereas using .attr('itemscope', '') shows the changes but as an attribute. In other words, as itemscope='' rather than itemscope.

What is the valid way to add an itemscope to an element with JS/jQuery?

var d = $("div");

d.attr('itemtype', 'http://schema.org/WebPage');
d.attr('itemscope', '');
d.prop('itemscope', true);
console.log(d.attr('itemtype'));
console.log(d.attr('itemscope'));
console.log(d.prop('itemscope'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div/>
unor
  • 92,415
  • 26
  • 211
  • 360
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239

1 Answers1

0

The itemscope attribute is a boolean attribute.

That means it can be specified in multiple ways (in the HTML syntax):

  • itemscope
  • itemscope=""
  • itemscope=''
  • itemscope=itemscope
  • itemscope="itemscope"
  • itemscope='itemscope'

(and variants with upper/mixed case and additional spaces at certain positions are possible, too)

(References from HTML 5.1: 2.4.2. Boolean attributes, 8.1.2.3. Attributes)

For adding it with JavaScript, see for example the question How to add boolean attribute using JavaScript.

Community
  • 1
  • 1
unor
  • 92,415
  • 26
  • 211
  • 360