I have a string variable called the res.
Within this variable there is HTML code.
Each Div in variable within the has a id.
var res = "<div id="1">1</div>
<div id="2">12</div>
<div id="3">123</div>
<div id="4">1234</div>";
var content-div-1 = ??;
var content-div-2 = ??;
var content-div-3 = ??;
var content-div-4 = ??;
I would like to give the id of div and give me values of inside Div.
The question has been answered, but there's an alternative without jQuery
var res = '<div id="1">1</div>'+
'<div id="2">12</div>'+
'<div id="3">123</div>'+
'<div id="4">1234</div>';
function findMe(txt, id){
var matches = txt.match(new RegExp('<div\\s+id="'+id+'">[\\S\\s]*?<\\/div>'), 'gi');
if(matches) return matches[0].replace(/(<\/?[^>]+>)/gi, '');
return '';
}
var content1 = findMe(res,1);
var content2 = findMe(res,2);
var content3 = findMe(res,3);
var content4 = findMe(res,4);
JSFiddle
As you've tagged your question jquery, I assume this is in a browser context (or some other context with a DOM). If so, the simplest way to is to parse the HTML and use the resulting disconnected DOM tree:
var res = '<div id="1">1</div>' +
'<div id="2">12</div>' +
'<div id="3">123</div>' +
'<div id="4">1234</div>';
var parsed = $(res);
var contentDiv1 = parsed.filter("[id=1]").text(); // See note below
snippet.log("1: " + contentDiv1);
var contentDiv2 = parsed.filter("[id=2]").text(); // See note below
snippet.log("2: " + contentDiv2);
// ...and so on (or use a loop)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note: Although id value starting with digits are valid HTML, it's awkward to use them because in a CSS id selector (#foo), you can't start the ID value with an unescaped digit (e.g., #1 is an invalid selector). That's why I've had to use the attribute selector [id=1] above. You can work around it with escaping, but by far the best option is just to not start ID values with digits in the first place.
Related
I have this string (not html but string):
<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>
Need to extract text value of rTag so result should be a new string:
ATINA,BELMOPAN,DAMASK,FILIPINI,BANGKOK
Any help?
This will set the content of #output to the new str, but you can do whatever you want after its joined.
var str = [];
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var $html = $($.parseHTML("<div>" + content + "</div>"));
$html.find(".rTag").each(function(){
str.push($(this).html());
});
$("#output").html(str.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="output"></div>
Parsing an HTML string into a DOM element so that it can be processed by javascript/jquery is a fairly standard process:
$(content)
will suffice without needing to add it to the DOM (and all that entails behind the scenes).
In this case:
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var arr = $(content).filter(".rTag").map(function() {
return $(this).text();
}).get();
console.log(arr.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have a string with some variable html saved inside, among which a div with static id="time",
example:
myString = "<div class="class">blahblah</div><div id="time">1:44</div>"
How can I create a new identical string cutting off only the time? (1:44 in this case).
I can't look for numbers or the ":" because is not safe in my situation.
What i've tried without success is this:
var content = divContainer.innerHTML;
var jHtmlObject = jQuery(content);
var editor = jQuery("<p>").append(jHtmlObject);
var myDiv = editor.find("#time");
myDiv.html() = '';
content = editor.html();
console.log('content -> '+content);
var myString = '<div class="class">blahblah</div><div id="time">1:44</div>';
//create a dummy span
//put the html in it
//find the time
//remove it's inner html
//execute end() so the jQuery object selected returns to the span
//console log the innerHTML of the span
console.log($('<span>').html(myString).find('#time').html('').end().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can achieve this using a regular expression in plain javascript like so:
myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')
If you want to extract only the 1:44 portion you can use the following:
myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]
I have this source
<div class="page"><h1>First Page </h1></div>
How can I convert it to html and use selector like $('.page') ? I tried to assign above string to a variable then use html() it doesn't work.
You can parse your string in HTML, after that if you look the object returned, there's a data property on the first row who contain the html string with good format.
EDIT
You can get HTML object properties without append it to the DOM. Check my edited code.
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
You can try this :
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
$("body").html(testHTML[0].data);
$(".page").css("color","blue");
//Without append element in the DOM
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
//For count number of element you can use a container without append it to the DOM
var container=$("<div></div>");
container.append(elemHTML);
console.log(container.find(".page").length);
.page{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
See comments, first we have to process the entities, then use the result as HTML:
// The string
var str = '<div class="page"><h1>First Page </h1></div>';
// A wrapper element to put it in
var wrapper = $("<body>");
// Process the character entities
wrapper.html(str);
str = wrapper.text();
// Convert the resulting HTML to a structure
wrapper.html(str);
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That's verbose for clarity; here's the concise version:
var str = '<div class="page"><h1>First Page </h1></div>';
var wrapper = $("<body>");
wrapper.html(wrapper.html(str).text());
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use following script for this
$('.page').html('<div class="page"><h1>First Page </h1></div>');
or
var htmlString = '<div class="page"><h1>First Page </h1></div>';
$('.page').html(htmlString);
Jquery automatically convert it to html
I have a JavaScript map that looks like this
var code = {'as':'','db':'','id3':'','term':''};
And want to print for example as into a div. If I do this, I get 'Undefined' inside the div. As I understand, this means the value itself is undefined. How can I "predefine" the empty string?
Update:
As there seems to be a lot of confusion: If I put code[1] into a div using the code above, the div contains 'Undefined'.
Update:
The markup looks as follows
<div id="cont" class="diff">
<div id="editor">
<div id="funcRow">
<ul>
<li><a onclick="changeTab(0)">Settings</a></li>
<li><a onclick="changeTab(1)">Knowledge</a></li>
<li><a onclick="changeTab(2)">Layer 4</a></li>
<li><a onclick="changeTab(3)">Hardware</a></li>
</ul>
</div>
<div id="text" contenteditable=true>
</div>
</div>
</div>
and changeTab(i) looks as follows:
function changeTab(i) {
code[activeTab] = document.getElementById("text").innerHTML;
document.getElementById("text").innerHTML = code[i];
document.getElementsByTagName("ul")[0].getElementsByTagName("li")[i].getElementsByTagName("a")[0].className="active";
document.getElementsByTagName("ul")[0].getElementsByTagName("li")[activeTab].getElementsByTagName("a")[0].className="";
activeTab = i;
}
The code below should be self-explanatory, just stringify before outputting
var div = document.getElementById('test');
var code = {'as':'','db':'','id3':'','term':''};
div.innerHTML = '<pre>' + JSON.stringify(code, null, 4) + '</pre>';
<div id="test"></div>
If you just want to output one of the values, use the key to access it
var div = document.getElementById('test');
var code = {'as':'1','db':'2','id3':'3','term':'4'};
div.innerHTML = code.as; // dot notation, or "code['as']" for bracket notation
<div id="test"></div>
Try using for..in loop, .innerHTML ; using break to stop loop after as property printed to div
// "predefine" empty strings with `1` , `2, `3`, `4`
var code = {'as':'1','db':'2','id3':'3','term':'4'};
var div = document.querySelector("div");
for (var prop in code) {
if (prop === "as") {
div.innerHTML += code[prop];
break;
}
}
<div></div>
The problem was me trying to call code[i], which is not possible in JavaScript. Undefined popped up because JS tried to evaluate the value to the key, which was not present at first.
Like this, but since the value is "nothing", the output is "nothing".
var div = document.getElementById('test');
var code = {'as':'','db':'','id3':'','term':''};
// code['as'] = "hello, world"; // un-comment to see something
div.innerHTML = '[' + code['as'] + ']';
<div id="test"></div>
Here is a second idea, based on the revision of your question:
var div = document.getElementById('test');
var keys = ['as', 'db', 'id3', 'term' ];
var code = {};
for (var i = 0; i < keys.length; ++i) code[keys[i]] = '';
code['as'] = "hello, world";
// code[keys[0]] = "hello, world"; // or this
div.innerHTML = '[' + code['as'] + ']' + ' (' + code[keys[0]] + ')';
<div id="test">X</div>
I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>