简体   繁体   中英

How to reach a html <span> tag inside a <div> using Java Script?

I've got a span tag which placed inside a div , like below:

<div onclick="doActiveCheckBox('color1')" id="sss"  class="test form-check form-option form-check-inline mb-2">
     <input class="test form-check-input" type="radio" name="color" id="color1" data-bs-label="colorOption" value="/تاریک" checked="">                                
     <label class="form-option-label rounded-circle" for="color1"><span style="border:inherit; border-block-color:purple;"  class="form-option-color rounded-circle" style="background-image: url(/img/ProductColors/green1.jpg)"></span></label>
</div>

I want to set a border for the span tag as the input tag is clicked and also don't want to use any id in the span . I've tried the bellow ways:

1:

        var d=document.getElementById("sss").getElementsByTagName("span");
        d.style.border = "thick solid #0000FF";

2:

        var d=document.getElementById("sss").getElementsByClassName();
        for (var i = 1; i <= d.length; i++) {
            d[1].style.border = "thick solid #0000FF";
        }

but none of them worked correctly? So would anybody help?

I would suggest to use querySelector: const d = document.querySelector("#sss span");

And then you can add style: d.style.border = "thick solid #0000FF";

  var d=document.getElementById("sss").getElementsByTagName("span");
                                                 ^//returns an array
d.get.style.border = "thick solid #0000FF";//d[0].style
//┗━━┛ 

There is not a property called get , so access the first element since getElementsByTagName return an array.

To get the span you can do this

var span = document.querySelector("#sss label span");
//do whatever you want with the span

Jquery method if needed

var span = $("#sss label span");
span.css("border", "thick solid #0000FF");

or if you're not using #sss just the inputs (may get multiple results)

var span = $("input.form-check label span");

You could Do These steps to get any HTML ELEMENT and STYLE it using CSS or use it using JS by document.querySelector
1.
在此处输入图像描述

2. 在此处输入图像描述

3. 在此处输入图像描述

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