Get id from string using javascript - 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);

Related

clone or append a variable in a new div?

I have this Html <h1 class="count" role="status">Search results 546</h1>
I'm trying to clone only the numerical '546' of that div and display it inside another div 'h2.count'
I manage to call only the numerical value in an alert via:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(0));
Otherwise , when i try to make it display in the div h2.count instead of an alert, it is not working.
I have try the below:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$parsedPrice.appendTo('h2.onlycount');
Any thought of what i am doing wrong ?
Thanks a lot guys !
I guess that your two html elements are unique so, using id's instead of classes (and native js), try this :
html :
<h1 id="count">Search results 541</h1>
<h2 id="onlycount"></h2>
js :
var price = document.getElementById('count').innerText;
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
document.getElementById('onlycount').innerText = parsedPrice;
https://jsfiddle.net/f3rj2bnv/
And if you want to keep on using jQuery (replace "#" with "." if you want or have to use classes instead of ids in your html elements) :
var price = $('h1#count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2#onlycount').text(parsedPrice)
The content used by .appendTo() should be
"a selector expression or as markup created on the fly"
Since in your example neither is true, try this:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2.onlycount').text(parsedPrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount" role="status"></h1>
Can use text(function)
$('h2.onlycount').text(function(_, existingText){
return existingText + $('h1.count').text().replace(/([^0-9\.])/g, '');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount"></h2>

get html from a variable by id

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();

Create custom variable names

I have an orientational question that i'm not quite sure how to approach, so this is a request for advice.
For a project i'm working on i would like to assemble 'custom' variable names. For example, lets say i have this html page:
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Now i know i can get the id's in jQuery with $('div').attr('id'). This is where my problem comes in:
I would like to create something like this line:
var variable_name_custom = 'Hello world';
where the var-name is generated by getting the div id's. (string div 1 + string div 2 + string div 3).
If i were to put the 3 names together right now, i would get the string 'variable_name_custom', but it would be a string-value of a variable, rather than the name of one.
Is this possible?
I have no idea why you would want to do something like this but:
var varName = getName(); // will get you 'div1_div2_div3'.
window[varName] = 'Hello world';
alert(div1_div2_div3); // Hello World.
Now you can access the div1_div2_div3 global var you created.
Take a look at this Fiddle
Here you go: http://jsfiddle.net/lotusgodkk/wd99s/
window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')] = 'Sample';
console.log(window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')]);
<div id="variable"></div>
<span id="name"></span>
<p id="custom"></p>
I think your best bet is to change the var into a property of an object.
names = {};
names[id1+'_'+id2+'_'+id3] = 'Hello world';
Hi you can use map function of Jquery
HTML Code
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Javascript
$(document).ready(function () {
var varname = $("#content > div").map(function () {
return this.id || null;
}).get().join("_");
window[varname] = "Hello World";
console.log("varname = "+varname);
console.log("value = "+window[varname])
});
take a look at this fiddle
Hope this helps
Thanks,
Dhiraj

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();

jQuery - how to select a variable's suffix and find its match in an array

I have an array of options:
var options = ["foo_A", "foo_B", "foo_C", "foo_D"];
...and when a user clicks on one of the following elements...
<div id="bar_A"> </div>
<div id="bar_B"> </div>
<div id="bar_C"> </div>
<div id="bar_D"> </div>
...it sets the following variable:
var currentBar = $(this).attr('id');
...and then I'd like to search through the options array and find the item whose suffix matches that of currentBar, something like this:
$.each(options, function(i,v){
if (v's suffix matches the currentBar's suffix){
//function to do something
}
$.each(options, function(i,v){
if (options[i].split("_")[1] == currentBar.split("_")[1]){
//function to do something
}
You need to use split function on currentBar
var Extract = currentBar.split('_');
// Extract[0] will be bar and Extract[1] will be the letter
After, second value will be the letter and will match.
var Key = indexOf('foo_' + Extract[1], options);
alert(options[Key]);

Categories

Resources