• Parent 1
    • Child 1
    • Child 2
      • Parent 1
        • Child 1
        • Child 2
          • Parent 1
            • Child 1
            • Child 2
            • TechQA.

              Set element ID on page load with Jquery?

              3.4k views Asked by Nấm Lùn At 2013-12-05T11:16:02+00:00 05 December 2013 at 11:16 2025-12-25T01:42:40+00:00

              Assume that I have some HTML elements like these:

              <div id="wrapper">
                  <ul>
                      <li><a>Parent 1</a>
                          <ul>
                               <li><a>Child 1</a></li>
                               <li><a>Child 2</a></li>
                               <li><a>Child 3</a></li>
                          </ul>
                      </li>
                      <li><a>Parent 2</a>
                          <ul>
                               <li><a>Child 1</a></li>
                               <li><a>Child 2</a></li>
                               <li><a>Child 3</a></li>
                          </ul>
                      </li>
                  </ul>
              </div>
              

              How can I set the ID for the first UL element in the #wrapper when $(document) ready??

              Thanks in advance!

              jquery set attr pageload document-ready
              Original Q&A
              4

              There are 4 answers

              0
              GautamD31 GautamD31 On 2013-12-05T11:17:58+00:00 05 December 2013 at 11:17 BEST ANSWER

              Try with :first like

              $('#wrapper ul:first').attr('id', 'customeId');
              

              Or you can try with :eq(0) like

              $('#wrapper ul:eq(0)').attr('id', 'customeId');
              

              Even(May be) you can try with .eq(0) like

              $('#wrapper ul').eq(0).attr('id', 'customeId');
              

              Make sure that you have this script on DOM ready like

              $(document).ready(function(){
                  $('#wrapper ul:first').attr('id', 'customeId');
              });
              

              And please correct your html because it is breaking while closing ul

              0
              Adil Adil On 2013-12-05T11:16:53+00:00 05 December 2013 at 11:16

              Like this.

              Live Demo

              $(document).ready(function(){
                  $('#wrapper ul:first').attr('id', 'yourid');
              });
              

              You have invalid html as well, you missed the closing ul

              <div id="wrapper">
                  <ul>
                      <li><a>Parent 1</a>
                          <ul>
                               <li><a>Child 1</a></li>
                               <li><a>Child 2</a></li>
                               <li><a>Child 3</a></li>
                          </ul>    
                      </li>
                      <li><a>Parent 2</a>
                          <ul>
                               <li><a>Child 1</a></li>
                               <li><a>Child 2</a></li>
                               <li><a>Child 3</a></li>
                          </ul>     
                      </li>
                  </ul>
              </div>
              
              0
              Anoop Joshi P Anoop Joshi P On 2013-12-05T11:18:26+00:00 05 December 2013 at 11:18
                 $(document).ready(function () {
                  $("#wrapper").children("ul").attr("id", "myid");
                 });
              
              0
              Prateek Prateek On 2013-12-05T11:18:33+00:00 05 December 2013 at 11:18

              Use .attr

              $("#wrapper ul:first").attr("id","id");
              

              Related Questions in JQUERY

              • In Datatables, start value resets to 0, when column sorting
              • Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
              • window.location.href redirects but is causing problems on the webpage
              • Using JQuery Date Slider
              • Storing selected language in localStorage
              • How to stop other divs from still showing when i click a different button?
              • Check multiple values with jQuery
              • Bootstrap component does not want to render in Datatables function
              • put white spaces when entering an amount moneytype symfony
              • Trouble accessing custom header in AJAX response using jQuery in Fiware Keyrock
              • I just cant make it work, HTML, JS and Firebase error
              • Didn't declared variable still not getting any error in JavaScript
              • Move element horizontally while scrolling vertically in pure JavaScript
              • allow multi carousel in same page
              • Embedded TikTok posts / thumbnail styling issue

              Related Questions in SET

              • mondrian3 set by aggregate
              • Produce a combination of all permutations for 4 groups of data with 4 unique values contained
              • How to find the difference between two python files and write output with file source information
              • Is there a problem with my code? Finding null pointer Exception
              • The difference between set definitions in Python
              • Leetcode BFS Set insertion giving TLE (200. Number of Islands)
              • set.find() not working for ordered multiset
              • TinyMCE custom toolbar button to set CSS property of selected text
              • Find a bit with no duplicates among multiple bits in Java
              • Algorithm for comparing two sets of sets
              • Order of a set in Python
              • Proof on inductive sets
              • Remove all elements from a set greater than a number
              • Trying to prove a set to be the union of its singleton sets in Dafny
              • Declaring a set of a set in Mosel

              Related Questions in ATTR

              • How do I use Rust to read a HDF5 string attribute of a dataset using the hdf5-rust crate?
              • how to assign an attribute to some variables using another data frame?
              • Using class methods to return instances and simply defining __init__(self, **kwargs):
              • extracting column attribute inside a function
              • How to html text show as par this attribute in jQuery?
              • What is difference between binding to attribute and binding to property in Angular?
              • How to mypy typehint an attrs validator attribute
              • Undefined 'href' attribute/jQuery
              • How to remove HTML attribute starting with letter + number?
              • How to remove the "locked" flag (programmatically)
              • How to get a css property using css?
              • Cheerio does not retrieve disabled attribute
              • Obtain drawable from ?android:attr programatically
              • Applying attrs.frozen in metaclass removes Python type annotations
              • Use dynamic defaults for Python's attr package when creating model

              Related Questions in PAGELOAD

              • delay in page load when moving from client slide page to ssr page in nextjs
              • How can I stop slideout on subsequent page load?
              • Calling a stored procedure on page-load in ASP.NET webforms using VS 2019
              • Page not opening but URL is entered in browser in Selenium Java with Cucumber Automation
              • Setting a component's variable to localStorage / global variable value on the initial render
              • Website flashing for a few frames when navigating between subpages while logged in wordpress
              • How to disable css transition load with given script
              • How to start sound after page load and change by click function
              • Selenium unable to stop page loading
              • Disable button if dropdownlist is null
              • React Pages Load white page
              • Redirecting to a content page in ASP.NET C# but page_load is fired multiple times with different urls including JS
              • Why my element undefined in code but defined if I run the code in console js?
              • Performance of page load with multiple scripts and HTTP multiplexing
              • Yii2 Page doesn't always load content properly until refresh

              Related Questions in DOCUMENT-READY

              • How to fix AsyncStorage has been removed from react-native core
              • Is this $(document).ready being fired twice?
              • how to get the value of a radio button that is in a label in div inside document.ready
              • Why don't the buttons inside of my $(document).ready(function () call work when clicked?
              • window DOMContentLoaded vs document DOMContentLoaded
              • How can Chrome be forced to favor the anchor specified in URL over the last scrollbar position?
              • Python Selenium: Switch tab without waiting for page to load
              • Can Selenium detect when webpage finishes loading in Python3?
              • How to execute JavaScript code when click Button in Webflow
              • Javascript not firing with dynamically loaded form and scripts
              • How to pass a variable from html to a document ready function
              • What is the most efficient way to check if element exists in Selenium
              • How to make HTML filterable by every column (independently) using JavaScript?
              • How to display a username in jQuery( document ).ready?
              • Why does the ready event not fire if the function is async

              Popular Questions

              • How do I undo the most recent local commits in Git?
              • How can I remove a specific item from an array in JavaScript?
              • How do I delete a Git branch locally and remotely?
              • Find all files containing a specific text (string) on Linux?
              • How do I revert a Git repository to a previous commit?
              • How do I create an HTML button that acts like a link?
              • How do I check out a remote Git branch?
              • How do I force "git pull" to overwrite local files?
              • How do I list all files of a directory?
              • How to check whether a string contains a substring in JavaScript?
              • How do I redirect to another webpage?
              • How can I iterate over rows in a Pandas DataFrame?
              • How do I convert a String to an int in Java?
              • Does Python have a string 'contains' substring method?
              • How do I check if a string contains a specific word?

              Trending Questions

              • UIImageView Frame Doesn't Reflect Constraints
              • Is it possible to use adb commands to click on a view by finding its ID?
              • How to create a new web character symbol recognizable by html/javascript?
              • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
              • Heap Gives Page Fault
              • Connect ffmpeg to Visual Studio 2008
              • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
              • How to avoid default initialization of objects in std::vector?
              • second argument of the command line arguments in a format other than char** argv or char* argv[]
              • How to improve efficiency of algorithm which generates next lexicographic permutation?
              • Navigating to the another actvity app getting crash in android
              • How to read the particular message format in android and store in sqlite database?
              • Resetting inventory status after order is cancelled
              • Efficiently compute powers of X in SSE/AVX
              • Insert into an external database using ajax and php : POST 500 (Internal Server Error)
              • Privacy
              • Terms
              • Cookies
              • Homegardensmart
              • Math
              • Aftereffectstemplates