1

I have textarea element. When a user types some HTML code inside the textarea, the function should find the body element.

The HTML code

<textarea id="textarea_code" ></textarea>
<a href="" onclick="check()">Check element</a>

The JavaScript function:

function check()
{
var codecheck = document.getElementById('teatarea_code').getElementsByTagName('body');

 if(codecheck)
 {
 alert('Yes, textarea has body element.');
 }
}
John
  • 1
  • 13
  • 98
  • 177
  • html code is missing and whats exactly is the query? – Manrah Jun 15 '19 at 06:56
  • You might find [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) useful. Also see [Parse an HTML string with JS](https://stackoverflow.com/questions/10585029/parse-an-html-string-with-js). – showdev Jun 15 '19 at 07:00
  • Possible duplicate of [How to check if element exists in the visible DOM?](https://stackoverflow.com/questions/5629684/how-to-check-if-element-exists-in-the-visible-dom) – Prashant Pimpale Jun 15 '19 at 07:03
  • 1
    @PrashantPimpale It seems that the element is not in the DOM. It's a string entered into a ` – showdev Jun 15 '19 at 07:04
  • @showdev Vote Extracted! – Prashant Pimpale Jun 15 '19 at 07:06

3 Answers3

1

In the future search the web for either "string in string" or "string substring".

if (document.getElementById('textarea_code').value.indexOf('<body') > -1)
{
 alert('Yes, textarea has body element.');
}

As a proper (and semi-dynamic) function:

function substring_search(e,ss)
{
 //e = element
 //ss = substring

 return (document.getElementById(e).value.indexOf(ss) > -1) ? true : false;
}

Also avoid camelCase, use underscores for code (and dashes for URLs) to both objectively and visually differentiate your code.

John
  • 1
  • 13
  • 98
  • 177
0

The variable codecheck will not return true if there is content inside body tag, but will return true when there is a body tag which obviously is. So the function always gives an alert message irrespective of whether it has content inside the body tag or not until the body tag exists.

John S
  • 1
  • 2
0

In textarea we can check that it contains the substring or not

document.getElementById("myTextarea")value.includes('<body>').
Manrah
  • 556
  • 3
  • 13