简体   繁体   中英

Get the value of Span class inside a Select Option

I know it might seem a duplicate but its not.

Here is what my select looks like:

<select id="avpMy4Y7E4cH_-iIRmmAK6-2GsEOu6Sjr-0-0"> 
 <option value="1Ltr [ <span class=money>Rs.1,495.00</span> ]">...</option> 
</select>

I want to get the value of the class "money" only.

Here is what I tried:

var val = $('#avpMy4Y7E4cH_-iIRmmAK6-2GsEOu6Sjr-0-0 option:selected').find('.money').val();

But this return empty value.

How can I get that specific value?

I'm a bit unclear as to what you want returned, but this will return the textContent of the span as well as the classNames . Span elements don't have value properties.

You can use DOMParser to convert the selected option text to an HTML document, select the elements from the document matching that selector, and extract the textContent

 window.addEventListener("DOMContentLoaded", () => { const opt = document.querySelector('#avpMy4Y7E4cH_-iIRmmAK6-2GsEOu6Sjr-0-0 option:checked'); const parser = new DOMParser(); //convert the value of the selected option to html document const htmldoc = parser.parseFromString(opt.value, "text/html"); //select all elements with className money from html document const moneys = htmldoc.querySelectorAll('.money'); //iterate each and display it's textContent moneys.forEach((a) => { console.log(a.textContent); //if you want to read the classNames a.classList.forEach((b) => { console.log(b); }); }); });
 <select id="avpMy4Y7E4cH_-iIRmmAK6-2GsEOu6Sjr-0-0"> <option selected value="1Ltr [ <span class=money>Rs.1,495.00</span> ]"></option> </select>

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