avaris
avaris

Reputation: 41

check if <p> contains a word of it's value

Having trouble getting this to work. Can't get .includes to work with values and i'm unsure why

Here is a working example using zxzx as a variable instead of a value as i want:

<p id="content">Lorem ipsum dolor sit amet</p>
<button onClick="scale()">button</button>

function scale() {
var zdzd = document.querySelector('#content');
var xzxz = "Lorem"

if(zdzd.innerHTML.includes(xzxz)){

zdzd.style.transform = "scaleY(0.8)";

}}

Not working with .value:

<p id="content" value="Lorem">Lorem ipsum dolor sit amet</p>
<button onClick="scale()">button</button>

function scale() {
var zdzd = document.querySelector('#content');

if(zdzd.innerHTML.includes(zdzd.value)){

zdzd.style.transform = "scaleY(0.8)";

}}

Any help appreciated

Upvotes: 3

Views: 57

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370819

Accessing the .value property of an element will only ever give you a result if you're dealing with an input-like element, such as a <textarea> or <input>. To retrieve an attribute name of value on a non-input element, you can't use dot notation - instead, look up the attribute with getAttribute:

function scale() {
  var zdzd = document.querySelector('#content');
  if (zdzd.innerHTML.includes(zdzd.getAttribute('value'))) {

    zdzd.style.transform = "scaleY(0.8)";

  }
}
<p id="content" value="Lorem">Lorem ipsum dolor sit amet</p>
<button onClick="scale()">button</button>

When you access the .value of a non-input element, you'll get undefined.

As the comment notes, it would be better not to use the value attribute for non-input like elements at all:

function scale() {
  var zdzd = document.querySelector('#content');
  if (zdzd.innerHTML.includes(zdzd.dataset.value)) {

    zdzd.style.transform = "scaleY(0.8)";

  }
}
<p id="content" data-value="Lorem">Lorem ipsum dolor sit amet</p>
<button onClick="scale()">button</button>

Upvotes: 1

Related Questions