1

I would like to find all elements which contains title on page and add new attribute to all of them.

Example:

<div title='something 1'></div>
<p>Test<div title='something 2'></div></p>
<div>
  <div>
    <div>
      <div title='something 3'></div>
    </div>
  </div>
</div>

How it should look like after page load:

<div title='something 1' rel='tooltip'></div>
<p>Test<div title='something 2' rel='tooltip'></div></p>
<div>
  <div>
    <div>
      <div title='something 3' rel='tooltip'></div>
    </div>
  </div>
</div>

Previously I did it manually which is bad solution for me

$('#collection_map > div > div > button').attr('rel', 'tooltip');
  • Possible duplicate of [How to get a DOM Element from a JQuery Selector](https://stackoverflow.com/questions/1677880/how-to-get-a-dom-element-from-a-jquery-selector) – GalAbra Jul 21 '19 at 17:06

3 Answers3

1

Try this code:-

$('div[title]').each(function() {
$(this).attr('rel', 'tooltip');
});
Dan
  • 71
  • 7
0

Get all elements which have attribute title and then loop over it to add new attribute rel to each object.

paragraph tag cannot have block elements like div nested in it. See - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p

Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing </p> tag.

 $('[title]').attr('rel', 'tooltip');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title='something 1'></div>
<p>Test
  <div title='something 2'></div>
</p>
<div>
  <div>
    <div>
      <div title='something 3'></div>
    </div>
  </div>
</div>
random
  • 7,756
  • 3
  • 19
  • 25
0

You don't even need jQuery for this. Here is a working example in plain JavaScript.

var elems = document.querySelectorAll('[title]')

elems.forEach(elem => elem.setAttribute('rel', 'tooltip'))
<div title='something 1'></div>
<p>Test<div title='something 2'></div></p>
<div>
  <div>
    <div>
      <div title='something 3'></div>
    </div>
  </div>
</div>
Todd Chaffee
  • 6,754
  • 32
  • 41