Search code examples
htmljquerydivi

How to add a specific metadata using jquery into a div with an ID


I am trying to figure out how to write jQuery code to insert meta data in to an element, specifically this: data-section-name="home"

I want to insert this in a div with an ID of home-section and the output would be like this:

<div id="home-section" data-section-name="home">
  (some code here...)
</div>

I am using a divi builder in Wordpress


Solution

  • If you need the data attribute to appear in the HTML source use attr():

    $('#home-section').attr('data-section-name', 'home');
    

    If the data attribute is going to be read by a jQuery library then you can use the data() method instead, which is more performant:

    $('#home-section').data('section-name', 'home');
    

    The caveat in both cases is to ensure that you execute this line of code before whatever library depends on that data attribute being present.