1

I have a function where I am trying to get a value from an onclick event.

Here is the element attribute that gives the function to the element:

listcontainer.setAttribute('onmousedown',"knowbe4campaignspecific(this)")

Here is the function code:

function knowbe4campaignspecific(ele){
    console.log(ele.value)}

However it will say undefined in the developer console.

If I just print the element by itself it will show the value inside so I must be missing something basic.

function knowbe4campaignspecific(ele){
    console.log(ele)}

##RESULTS##
<ul value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>

Let me know if anything else is needed and I will update this post. Thanks!

1
  • 2
    <ul> elements do not have a value property. You may be interested in data attributes if you want to assign and access arbitrary data Commented Dec 5, 2021 at 23:13

2 Answers 2

2

As mentioned, value isn't a valid attribute of <ul>. You can still use it and access it through element.getAttribute but using datasets is more extendable and the correct implementation - you can access those through element.dataset

document.querySelector('.ms-List').setAttribute('onmousedown',"knowbe4campaignspecific(this)")

function knowbe4campaignspecific(ele){
    console.log(ele.getAttribute('value'))
    console.log(ele.dataset.value)
}
<ul value="183085" data-value="This is the better way" class="ms-List"><li> something</li></ul>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me out as well! I think learned a little more from you since I learned you can use element.getAttribute to find value. I am using datasets now as that seems great, but I just wanted to say thanks for that extra bit of information :)
0

On elements that are not inputs you want to use the data attribute.

I believe this should work

<ul data-value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>

And then

function knowbe4campaignspecific(ele){
    console.log(ele.dataset.value)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.