get html from a variable by id - javascript

i have a variable name value in my javascript code that contain html data.i want to get the data inside form specific id that is inside #myDiv
var value="<div >
<p class="">Hi cname#gmail.com</p>
<br/>
<br/>
<br/>
<div id="myDiv">
sgdhsagdhagh
dhsajdgasj
cjzjcg
</div>
</div>"
Thanks

You should create a DOM element, then traverse up to it and get html() or .text()
var value = '<div >\
<p class="">Hi cname#gmail.com</p>\
<br/>\
<br/>\
<div id="myDiv">\
sgdhsagdhagh\
dhsajdgasj\
cjzjcg\
</div>\
</div>';
alert($(value).find('#myDiv').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you need to get parent element, then use
alert($('<div />', {html: value}).find('#myDiv').html())

How about you do like this?
var variable = "stuff n things";
document.getElementById( 'myDiv' ).innerHTML = variable;
Thats the native way :)
EDIT:
if you want to get the data you just do like this:
var variable = document.getElementById( 'myDiv' ).innerHTML;
That will give you the markup of whats inside the div.
Or use document.querySelector("#myDiv") to get the first match on the selector.querySelectorAll returns array.

You can use the HTML of the value variable to create an jQuery object. From this object you can search for the element with the id, and get its HTML content:
var html = $(value).find('#myDiv').html();
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Or a pure javascript implementation:
var el = document.createElement('div');
el.innerHTML = value;
var html = el.getElementById('myDiv').innerHTML;
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg

Using plain Javascriptuse:
document.getElementById("myDiv").innerHTML;
Using jQuery:
$("#myDiv").html();

There are Two ways- Angular way-
var elem = angular.element(value);
var innerDive=elem[0].getElementById('myDiv');
var text= angular.element(innerDive[0]).innerText;
Jquery-
var text= $(value).find('#myDiv').text();

Related

selecting element from a html string inside variable

I have html string data inside variable like this
var htmlstring = "<div><div class='testdiv'>924422</div></div>"
What I am expecting is to fetch content of div having class.In this example .testdiv data.
How can I achieve?.
I know one approach: Append this html string to html page and then access.But I dont want to do it as I am using ajax and server returning kind of html string.Now I want to fetch data inside specific div.
So is there any alternative way to do?
First you don't use . in class name in html. And to fetch the content of that div in html string, you could use jquery find function.
var htmlstring = "<div><div class='testdiv'>924422</div></div>"
alert($(htmlstring).find('.testdiv').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a way you can achieve it without jQuery.
var htmlstring = "<div><div class='testdiv'>924422</div></div>";
function getTestDiv(htmlString) {
var textVal = null;
var div = document.createElement('div');
div.innerHTML = htmlString;
var elements = div.childNodes;
if (elements.item(0).childNodes.item(0).className === 'testdiv') {
textVal = elements.item(0).childNodes.item(0).innerHTML;
}
return textVal;
}
console.log(getTestDiv(htmlstring));
You can do this by :
console.log($(htmlstring).find("div.testdiv").text());

Javascript Replace all but what is inside of title=""

I have this text
var test = "<span data-toggle="tooltip" title="2Test">1TEST</span>";
I don't rely not sure what I am doing and could need some help. This is what I tried:
test = test.replace(/<span data-toggle="tooltip" title="|">[^>]*>/gi, "");
The test variable should only return the value inside of "title".
I agree with #Biffen you shouldn't really parse HTML with regex! But if you must do it, try this...
var test = "<span data-toggle='tooltip' title='2Test'>1TEST</span>";
var result = test.match(/title='([^']+)'/)[1];
console.log(result); //2Test
You don't need to parse HTML to get the title attribute, instead you can access title attribute from HTML DOM.
Create a temporary container with createElement, then set inner html with your html string, lastly traverse to first child which is the span and get the title attribute that you want.
Example:
var test = "<span data-toggle='tooltip' title='2Test'>1TEST</span>";
var el = document.createElement('div');
el.innerHTML = test;
var title = el.firstChild.getAttribute('title')
console.log(title) //2Test

Get id from string using javascript

I have this simple string:
<div id="parent">
<div id="1" class="child">test</div>
</div>
How can I extract the id number (1) from this string?
With JQuery you can
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var str = $('<div id="parent"><div id="1" class="child">test</div></div>');
console.log(str.find(':nth-child(1)').attr('id'));
</script>
Where nth-child is the target you want to get the id
var s = '<div id="parent"> <div id="1" class="child">test</div> </div>';
var d = new DOMParser().parseFromString( s, "text/xml" );
var id = d.firstChild.childNodes[1].attributes['id'];
console.log( id );
var htmlString = '<div id="parent"><div id="1" class="child">test</div></div>';
var number = /id="(\d)"/.exec(htmlString)[1];
console.log(number); //outputs the number
You would have to do a match on the string object that the HTML is stored in. so, if the string is called htmlString, then you would do something akin to
var id = htmlString.match(/id=\"([0-9]+)\"/)
That SHOULD net you the result, but if you deal with any data that is more complex than the example you've been given, you would need a different regex.
<script>
let num = document.getElementById('1')
let ans = parseInt(num.id)
</script>
Although I am unsure as to what you are trying to accomplish, one way of getting of doing this is s to gather all like tagnames ("div" in this case) into an array and select the array index you desire (1 in this case) then reference the id - as follows:
var list=document.getElementsByTagName("div")
alert(list[1].id);

Find div by value attribute and get html

I have some hidden divs with id's in html value attr. I want to find the div by value and get it's html. The problem is that my jQuery code returns undefined.
$( ".showComments" ).click(function() {
var id = $(this).closest('button').siblings('.writeComment').val();
var obj = $("#myDivs[value=id]").html();
alert(obj);
});
<div id='myDivs' value = '".$id."'>
<div>
<h3></h3>
<p></p>
</div>
</div>
I get the id correctly, but problem is when i tried get the divs html.
try:
var obj = $("#myDivs[value='"+id+"']").html();
console.log(obj);
Okay, that is wrong because it'll search for value="id" instead value="1" for example:
so you should do this:
var obj = $("#myDivs[value=" + id + "]").html();

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

Categories

Resources