简体   繁体   中英

Add HTML tag inside parent using JavaScript

I need to add a child HTML tag using JS to a parent without an ID or class (so I need to target the parent level up).

Here is what I have:

<div class="parent">
  <lavel>
    <input type="radio">
  </label>
</div>

Here is what I need:

<div class="parent">
  <lavel>
    <input type="radio">
    <span class="child-span">content</span>
  </label>
</div>

Any help? Thx.

Access the children of the parent:

 const el = document.createElement('span') el.classList.add('child-span') el.innerText = 'Hello!' document.querySelector('.parent').children[0].appendChild(el)
 <div class="parent"> <label> <input type="radio"> </label> </div>

Or query the element directly:

 const el = document.createElement('span') el.classList.add('child-span') el.innerText = 'Hello!' document.querySelector('.parent label').appendChild(el)
 <div class="parent"> <label> <input type="radio"> </label> </div>

IF jQuery is allowed

 $('.parent label').append('<span class="child-span">content</span>');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> <label> <input type="radio"> </label> </div>

Use document.getelementbyid to create a new div and then add what is required in that div.

Var newDiv = document.createElement("div"); 
                 //and give it some content 
                var newContent = document.createElement("");
                 //add the text node to the newly created div
                newDiv.appendChild(newContent);  
                //add the newly created element and its content into the DOM 
   var currentDiv = document.getElementById(""); 
            document.body.insertBefore(newDiv, currentDiv); 
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM