Search specific string from other HTML page? - javascript

I have been making a search functionality for the other HTML page. I am getting HTML from another page as a string and trying to parse that string to match data of all p's and heading tags. When it finds some specific string then it should return that p or heading with full text. The problem is that I am getting all the p's and headings and can't be able to iterate each element step by step.
Here is my jQuery code
$(document).ready(function()
{
$.get("file.html", function(html_string)
{
var parsed = $('<html/>').append(html_string);
$.each(parsed, function( i, el ) {
console.log(parsed.find("p").text());// here it is getting the text of all the p elements. But I need to iterate each p step by step so that I will be able to search my specific keyword
});
},'html');
});
file.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h3>Name</h3>
<p>Zain Farooq</p>
<h3>search</h3>
<p>Yes Search this</p><!-- When it finds this then it should return this-->
</body>
</html>
I have also used domparser but it is not giving me desired results

You should use .each function.
$.each(parsed, function( i, el ) {
parsed.find("p").each(function(index) {
console.log( index + ": " + $( this ).text() );
});
});

Related

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

using .parent() in jquery

I am trying to loop through a few divs.
Code:
$(".tree div ").each(function () {
var _searchthis = $(this);
var mySearchDiv = _searchthis.parent('div').attr('id');
console.log("this is ID : " + $(this).attr('id'));
console.log("this is parentID : " + mySearchDiv);
});
In case of ID, I am getting the value. But it does not return the .parent('div').attr('id')
I am getting "undefined".
Edited :
When I use .closest() ,instead of .parent(), I get the ID of $(this) only.
.parents('div').first().attr('id') also returns "undefined".
$(".tree li div ").each(function (){
....
}
was a desperate attempt.
HTML Code is more like: http://jsbin.com/yilaw/1/edit
===================================
RESOLVED. I had problem with my HTML structure. Thanks Guys.
Try changing your code to this:
_searchthis.parents("div").eq(0).attr('id');
.parent() parent goes only to the first level while .parents() goes up the stack.
Notice the difference here : http://jsbin.com/labugi/1/edit
html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="firstLevel">
<span id="secondLevel">
<p id="thirdLevel">
<i id="forthLevel">POC</i>
</p>
<span>
</div>
</body>
</html>
javascript
var result = $('#forthLevel').parent('div').attr('id');
console.log('result of .parent("div"): '+ result);
var result = $('#forthLevel').parents('div').attr('id');
console.log('result of .parents("div"): '+ result);
JQuery says about parent : http://api.jquery.com/parent/
The .parents() and .parent() methods are similar, except that the
latter only travels a single level up the DOM tree.
Use parents instead and get the first element like so : _searchthis.parents('div').eq(0);
Please note : the search query that you are using might be very slow, use classes or ids if possible instead of tagNames.

Retrieve text from search box

I'm building a program that allows me to search a document to see how many times a word appears within that document. I would like to choose which word to search by entering the desired word into a search box that I've built. Currently, If I hard code the word that I'm searching for, it'll search the document and tell me how times it appears. If I try to use the search box to enter a word, I always get a result of 0. I need a way to retrieve the word entered from the search box and use that word as the word that I want to check.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WordBubble</title>
<link rel="stylesheet" type="text/css" href="wordbubble.css">
<script type="text/javascript" src="jquery-1.10.2.js"></script>
</head>
<body>
<div id="search">
Search Word: <input type="search" name="Wordsearch" size="35">
<button type="submit" class ="searchme">Search</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".searchme").click(function(){
var myWord = $ (this).text();
findDuplicates();
});
});
// ajax call to get comments document
function findDuplicates (myWord) {
$.get( "comm.txt", function( text ) {
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = []
for (var i=0; i<sortedWords.length-1; i++) {
if (myWord == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
$( "p" ).html(duplicateWords.length);
});
}
</script>
<p></p>
</body>
</html>
In your click-handler you retrieve the searchstring from the button instead from the input.
$(document).ready(function(){
$(".searchme").click(function(){
// get the word from the input
var myWord = $('input').val();
findDuplicates(myWord);
});
});

How can I sort the data in a dynamically generated SELECT element with jQuery?

I am using JQuery to populate SELECT elements in order to cut down on the size of the outputted markup.
Everything is working the way I want except for one thing; the sorting.
It looks like by the time I get to the .each in the code below, the JQuery is sorting by the val value instead of the text value. I want the list sorted by the text value or more ideally, in the order that I generate the list in the variable dyn_list_product.
How can I accomplish this?
Many thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Sample Code</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type = "text/javascript" >
$(document).ready(function(){
var dyn_list_product = { 10075:'abc', 10635:'def', 10246:'ghi', 10245:'jkl', 10076:'mno', 10642:'pqr', 10995:'stu', 10255:'vwx', 10230:'yz' };
$('.jquery_list_product').append( $('<option></option>').val('').html('----------') );
$.each( dyn_list_product , function(val, text) { $('.jquery_list_product').append( $('<option></option>').val(val).html(text) ); });
})
</script>
</head>
<body>
<select name="insert-1[]" class="jquery_list_product"></select>
<select name="insert-2[]" class="jquery_list_product"></select>
<select name="insert-3[]" class="jquery_list_product"></select>
</body>
</html>
The jQuery code isn't sorting anything. The order of iteration through the keys of an object is undefined in JavaScript. That is, the fact that you defined the properties in some order means nothing about the order in which the .each() function will pass them to your handler.
Use an array instead:
var dyn_list_product = [ { key: '10075', val: 'abc'}, { key: '10635', val: :'def'}, ... ];
Your .each() loop will then look like:
$.each( dyn_list_product , function(index, obj) {
$('.jquery_list_product').append( $('<option></option>').val(obj.key).html(obj.val) ); });
})

Javascript Special Character removal not working

i have written a jsp code with values coming from other jsp and i need to remove the special characters in the string.But iam not able to remove special characters. Please help
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function change(chars){
var dchars=document.getElementById("chars").value;
dchars = dchars.replaceAll("!##$%^&*()+=[]\\\';,/{}|\":<>?", '');
document.getElementById("chars").innerHTML=dchars;
}
</script>
</head>
<%
String res=request.getParameter("tes");
%>
<body onload="change(chars)" ><script>
change(res)
</script>
<div id="chars"> <%=res%></div>
</body>
</html>
There is no "value" for div elements. You need to use innerHtml insted:
document.getElementById('chars').innerHTML = dchars;
try this....
document.getElementById('chars').innerHTML = dchars; //div has no value..
Assuming by special characters, you mean anything that's not letter, here is a solution:
alert(dchars.replace(/[^a-zA-Z ]/g, ""));
OR
alert(dchars.replace(/[^a-z0-9\s]/gi, '')); //will filter the string down to just alphanumeric values
The problem with using innerHTML is that certain characters are automatically converted to HTML entities such as & which is converted to &
function cleanCharsText(){
var el = document.getElementById("chars");
var txt = el.innerText || el.textContent;
el.innerHTML = txt.replace( /[!##$%^&*()+=\\[\]\';,/{}\|\":<>\?]/gi, '');
}
However if you have the following <span> text </span> inside your chars element the html span tags will be removed when you run the above function as we are only extracting the text.

Categories