I have the following code below. I want to change the H2 message No results were found for this query: <em class="querytext">to something like "No results were found by hello world! without hard coding as I have no control of the piece of text in an HTML file, is their any way I can do this via an if condition CSS or JS to read the string then change the message on load of the page? something like if text == No results were found for this query: display "No results were found by hello world!.
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em></h2>
</div>
You could try DOM manipulation with JavaScript:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script type="text/javascript">
function updateResultText(text) {
var resultTextEl = document.querySelector('.search-results > h2');
if(resultTextEl) {
resultTextEl.innerText = "No results were found by " + text;
}
}
</script>
<button onclick="updateResultText('hello world!')">Update Text</button>
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em>
</h2>
</div>
</body>
</html>
The JS you need is below:
function updateResultText(text) {
var resultTextEl = document.querySelector('.search-results > h2');
if(resultTextEl) {
resultTextEl.innerText = "No results were found by " + text;
}
}
You would then make the call to updateResultText with whatever you want the text following 'by ' to consist of.
Here's a solution that uses vanilla JS to change all h2 that are child of .search-results class:
for (let h2 of document.querySelectorAll('.search-results > h2')) {
if (h2.textContent.search('No results were found for this query') >= 0)
h2.textContent = 'No results were found by hello world!';
}
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em>
</h2>
</div>
old JavaScript
var query = "" // Get the username from either the backend, URL, or any other way like simple login form to the local storage without backend
var newText = 'No results were found for this' + query ': <em class="querytext"></em></h2>'
var el = document.querySelector('.search-results h2').innerHTML = newText
ES5
const query = "" // Get the username from either the backend, URL, or any other way like simple login form to the local storage without backend
const newText = `No results were found for this ${query}: <em class="querytext"></em></h2>`
const el = document.querySelector('.search-results h2').innerHTML = newText
At end of your page put the following script tag :
<script type="text/javascript">
var elem= document.querySelector('.search-results > h2');
if(elem) {
if(elem.innerText.indexOf("No results were found for this query")>=0)
elem.innerHtml="anything You want !!";
}
}
</script>
then after that there should be </body></html> tags.
Related
I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);
I have a webpage in which I want to display the articles headlines that I am fetching from NewYork Time API, I am using nodejs as well, but the problem is that my articles gets printed below the end of html, although it should be printed inside like the "SAMPLE TEXT" is getting printed, is there a way in which I can print it inside?
http://imgur.com/sNmbqeN
<div class="card">
<div class="header">
<h3 class="title"><center><b>Chronicle</b></center></h3>
</div>
<body>
<p id="headline">SAMPLE TEXT</p>
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.9/p5.js"></script>
<script>
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "removed",
'q': "Trump"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
var articles = result.response.docs;
for (var i=0; i<articles.length;i++)
{
document.createElement('div');
document.createElement("H1");
var h = document.createElement("H1");
var t = document.createTextNode(articles[i].headline.main);
h.appendChild(t);
document.body.appendChild(h);
}
}).fail(function(err) {
throw err;
});
</script>
</body>
Your articles are being inserted at the end of the page because that is what you are asking javascript to do in your "document.body.appendchild" line. If you want your retrieved articles to go in a specific div or p tag, do something like this:
<p id="articles">Articles listed below:</p>
<script>
var newArticle = document.createElement("div");
var h = document.createElement("H1");
h.appendChild(document.createTextNode("Header"));
newArticle.appendChild(h);
var t = document.createTextNode("New article text");
newArticle.appendChild(t);
document.getElementById("articles").appendChild(newArticle);
</script>
I can't test with your original code using the NYT api but you should be able to see how it's done at least with the code above.
OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>
I have a div in which I have to fill some data in. I have to render the HTML based on conditions and I am adding data to that div using jQuery. Can someone please tell me how I can add the condition based insertion of HTML on the page?
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
$('.myDiv').after("<br/>"+data);
}
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
data = data + "<p>The JSVariable is present on page </p>"
}
data = data + "</div>"
$('.myDiv').append("<br/>"+data);
}
function AddData(){
if(typeOf(jsVariable)!=="undefined"){
var data = "<div><h1>My data</h1>";
data += " <p>The JSVariable is present on page </p>";
data += "</div>";
$('.myDiv').after("<br/>"+data);
}
}
this should do the trick, but some element with a class of myDiv will need to already exist for this to work
<div class="myDiv"></div>
What exactly are you trying to do?
If you simply want to add some extra html content depending on the variable, you are almost done. You just need to add the <p> part to the data (data += "<p>...</p>").
If you're trying to add all of the html based on the variable, put the if statement around the $(".myDiv").after (which should be $(".myDiv").append btw).
You'r code is not valid.
Could you explain what do you want to do with
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
If you want to add a html code at ending of a div, you should use
$('.myDiv').append('<p>Text text text text</p>');
simple usage:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("p").click(function() {
var a = $("#div1").text();
if (a == "one") {
$("#div2").text(a);
}
});
});
</script>
</head>
<body>
<div id="div1">one</div>
<div id="div2"></div>
<p>click me</p>
</body>
</html>
function addData(to)
{
var h1 = $('<h1>').text('My Data');
var data = $('<div>').append(h1);
if (window.jsVariable) {
$('<p>').text('JS Variable is present on the page').appendTo(data);
}
to.append(data);
}
addData( $('.myDiv') );
if (condition) {
$('div#yourDivID').html('<p>The JSVariable is present on page </p>');
}
In addition to .html(which places the html inside your div), you can use other things like append, prepend etc. Check out jQuery's documentation on DOM Insertion.
Here is a JSFiddle http://jsfiddle.net/va4n8/
function addData() {
var newDiv = $('<div>');
newDiv.append($('<h1>').html('My data'));
if ('jsVariable' in window) {
newDiv.append($('<p>').html('The JSVariable is present on page'));
}
$('.mydiv').after($('<br>')).after(newDiv);
}
Though I've never heard of this but, is it possible to retrieve a node from the DOM using JS, and then find out on what line of the file that node occurred on?
I'm open to anything, alternative browsers plugins/add-ons etc...it doesn't need to be cross-browser per say.
I would assume that this would be possible somehow considering that some JS debuggers are capable of finding the line number within a script tag, but I'm not entirely sure.
Ok, forgive me for how large this is. I thought this was a very interesting question but while playing with it, I quickly realized that innerHTML and its ilk are quite unreliable wrt maintaining whitespace, comments, etc. With that in mind, I fell back to actually pulling down a full copy of the source so that I could be absolutely sure I got the full source. I then used jquery and a few (relatively small) regexes to find the location of each node. It seems to work well although I'm sure I've missed some edge cases. And, yeah, yeah, regexes and two problems, blah blah blah.
Edit: As an exercise in building jquery plugins, I've modified my code to function reasonably well as a standalone plugin with an example similar to the html found below (which I will leave here for posterity). I've tried to make the code slightly more robust (such as now handling tags inside quoted strings, such as onclick), but the biggest remaining bug is that it can't account for any modifications to the page, such as appending elements. I would need probably need to use an iframe instead of an ajax call to handle that case.
<html>
<head id="node0">
<!-- first comment -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style id="node1">
/* div { border: 1px solid black; } */
pre { border: 1px solid black; }
</style>
<!-- second comment -->
<script>
$(function() {
// fetch and display source
var source;
$.ajax({
url: location.href,
type: 'get',
dataType: 'text',
success: function(data) {
source = data;
var lines = data.split(/\r?\n/);
var html = $.map(lines, function(line, i) {
return ['<span id="line_number_', i, '"><strong>', i, ':</strong> ', line.replace(/</g, '<').replace(/>/g, '>'), '</span>'].join('');
}).join('\n');
// now sanitize the raw html so you don't get false hits in code or comments
var inside = false;
var tag = '';
var closing = {
xmp: '<\\/\\s*xmp\\s*>',
script: '<\\/\\s*script\\s*>',
'!--': '-->'
};
var clean_source = $.map(lines, function(line) {
if (inside && line.match(closing[tag])) {
var re = new RegExp('.*(' + closing[tag] + ')', 'i');
line = line.replace(re, "$1");
inside = false;
} else if (inside) {
line = '';
}
if (line.match(/<(script|!--)/)) {
tag = RegExp.$1;
line = line.replace(/<(script|xmp|!--)[^>]*.*(<(\/(script|xmp)|--)?>)/i, "<$1>$2");
var re = new RegExp(closing[tag], 'i');
inside = ! (re).test(line);
}
return line;
});
// nodes we're looking for
var nodes = $.map([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(num) { return $('#node' + num) });
// now find each desired node in both the DOM and the source
var line_numbers = $.map(nodes, function(node) {
var tag = node.attr('tagName');
var tags = $(tag);
var index = tags.index(node) + 1;
var count = 0;
for (var i = 0; i < clean_source.length; i++) {
var re = new RegExp('<' + tag, 'gi');
var matches = clean_source[i].match(re);
if (matches && matches.length) {
count += matches.length;
if (count >= index) {
console.debug(node, tag, index, count, i);
return i;
}
}
}
return count;
});
// saved till end to avoid affecting source html
$('#source_pretty').html(html);
$('#source_raw').text(source);
$('#source_clean').text(clean_source.join('\n'));
$.each(line_numbers, function() { $('#line_number_' + this).css('background-color', 'orange'); });
},
});
var false_matches = [
"<div>",
"<div>",
"</div>",
"</div>"
].join('');
});
</script>
</head>
<!-- third comment -->
<body id="node2">
<div>
<pre id="source_pretty">
</pre>
<pre id="source_raw">
</pre>
<pre id="source_clean">
</pre>
</div>
<div id="node3">
<xmp>
<code>
// <xmp> is deprecated, you should put it in <code> instead
</code>
</xmp>
</div>
<!-- fourth comment -->
<div><div><div><div><div><div><span><div id="node4"><span><span><b><em>
<i><strong><pre></pre></strong></i><div><div id="node5"><div></div></div></div></em>
</b></span><span><span id="node6"></span></span></span></div></span></div></div></div></div></div></div>
<div>
<div>
<div id="node7">
<div>
<div>
<div id="node8">
<span>
<!-- fifth comment -->
<div>
<span>
<span>
<b>
<em id="node9">
<i>
<strong>
<pre>
</pre>
</strong>
</i>
<div>
<div>
<div>
</div>
</div>
</div>
</em>
</b>
</span>
<span>
<span id="node10">
</span>
</span>
</span>
</div>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Something like this?
var wholeDocument = document.getElementsByTagName('html')[0]
var findNode = document.getElementById('whatever')
var documentUpToFindNode = wholeDocument.substr(0, wholeDocument.indexOf(findNode.outerHTML))
var nlsUpToFindNode = documentUpToFindNode.match(/\n/g).length
This can be done. Start by getting the highest node in the document like this:
var htmlNode = document.getElementsByTagName('html')[0];
var node = htmlNode;
while (node.previousSibling !== null) {
node = node.previousSibling;
}
var firstNode = node;
(this code was tested and retrieved both the doctype node as well as comments above the html node)
Then you loop through all nodes (both siblings and children). In IE, you'll only see the elements and comments (not text nodes), so it'll be best to use FF or chrome or something (you said it wouldn't have to be cross browser).
When you get to each text node, parse it to look for carriage returns.
You could try: -
- start at the 'whatever' node,
- traverse to each previous node back to the doc begining while concatenating the html of each node,
- then count the new lines in your collected HTML.
Post the code once you nut it out coz thats a good question :)