How to inject a number into HTML from a list? - javascript

What is the most convenient way of injecting a number into the HTML of the site (using Chrome Extensions), when the given parameter is found in the website's code? For example we have a list:
www.newsweek.com, hf-title, 2
www.aaa.com, yzs, 1
www.ccc.com, abc, 123
When we find "hf-title" on the website www.newseek.com then number "2" is inserted next to the found paragraph on the website in the browser. When we find "abc" in the code of the website www.ccc.com then number "123" is inserted next to the table, and so on.
There cannot be any connection to the database, just javascript.
The list that is going to be used will be hundreds of rows long, so it is really problematic to use switch statement.
The source table has to be located in the Google Chrome extension files on the PC. The information should be looked for when (or shortly after) the site is being opened.
Example of the source code:
<h2 class="hf-title">
Four NATO Allies Deny Ukraine<span class="overlay article-overlay"></span>
</h2>
<div class="hf-summary">
NATO officials have previously said... </div>
</div>
We add simply
<a> 2 </a>
at the end.
Any ideas? ;)

What you will likely need to do is find all of the text nodes on the page. From there you can begin editing them. The 'modifyTextNodes' function is an example of using a TreeWalker to do this. It is a very efficient method for traversing the DOM.
var arr = [{url:"www.newsweek.com", string:"hf-title", value:"2"},
{url:"www.aaa.com", string:"yzs", value:"1"},
{url:"www.ccc.com", string:"abc", value:"123"}];
function modifyTextNodes() {
var el = document.getElementsByTagName('html')[0];
var walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n = walk.nextNode()) {
modifyNode(n);
}
}
function modifyNode(node) {
if (node.nodeType == Node.TEXT_NODE && node.parentNode != undefined && (val = node.nodeValue.trim())) {
var addToEnd = "";
for (var i=0; i<arr.length; i++) {
if (document.baseURI.indexOf(arr[i].url) > -1 && val.indexOf(arr[i].string) > -1) {
addToEnd += arr[i].value;
}
}
}
if (addToEnd) {
node.nodeValue += addToEnd;
}
}
Alternatively, if it is elements that you are trying to find, you could use querySelectorAll to find all the matching elements.
document.querySelectorAll("[class='" + arr[i].string + "']");
In this case 'modifyAllNodes' would look like
function modifyAllNodes() {
for (var i = 0; i<arr.length; i++) {
if (document.baseURI.indexOf(arr[i].url) > -1) {
var nodes = document.querySelectorAll("[class='" + arr[i].string + "']");
modifyNodes(nodes, arr[i]);
}
}
}
function modifyNodes(nodes, arrEl) {
for (var i=0; i<nodes.length; i++) {
if (node.nodeValue.indexOf(arrEl.string) > -1) {
node.nodeValue += arrEl.value;
}
}
}

first you have to know the structure of the list you are trying to "hack", which means the ID or class names. Afterwards, in your JS check each record of that list if its content matches the string you pass to and then do a .append()

Related

Search entire DOM for number

I need to search my entire document for a phone number, and compile a list of elements which have this phone number in them.
However I have encountered afew snags.
I can't simply do document.body.innerHTML and replace the numbers, as this messes up third party scripts.
The following will match the elements, but ONLY if they have the number within them, and nothing else:
let elements = document.querySelectorAll("a, div, p, li");
let found = [];
for (let elm in elements) {
if (elements.hasOwnProperty(elm)) {
if (elements[elm].textContent !== undefined && elements[elm].textContent.search("00000 000000") != -1) {
found.push(elements[elm]);
}
}
}
So the following element will not match:
<li class="footer__telephone">
<i class="fa fa-phone" aria-hidden="true"></i>00000 000000
</li>
Due to having the i tag in there.
Using textContent instead of text also does not work as the parent of an element will then match, but I don't want the parent.
Edit:
<div class="row-block hmpg-text">
<div class="wrapper">
<div class="container">
<div class="row">
<div class="twelvecol">
00000 000000
</div>
</div>
</div>
</div>
</div>
Lets say the above is my HTML, if I loop through all the elements and test them with testContent then the first is going to be returned as true, to containing my number, but I need the element with the class of twelvecol on it, not the parent which is 4 levels up.
Managed to find an answer, similar to what Phylogenesis said however couldn't get any of them examples working.
function replaceText(el, regex_display, regex_link) {
// Replace any links
if (el.tagName === "A") {
if (regex_link.test(el.getAttribute("href"))) {
el.setAttribute("href", el.getAttribute("href").replace(regex_link, replacement.replace(/\s/g, '')));
}
}
if (el.nodeType === 3) {
if (regex_display.test(el.data)) el.data = el.data.replace(regex_display, replacement);
if (regex_link.test(el.data)) el.data = el.data.replace(regex_link, replacement);
} else {
let children = el.childNodes;
for (let i = 0; i < children.length; i++) {
replaceText(children[i], regex_display, regex_link);
}
}
}
let bodyChildren = document.body.childNodes;
let search_display = new RegExp(search, "g");
let search_link = new RegExp(search.replace(/\s/g, ''), "g");
for (let i = 0; i < bodyChildren.length; i++) {
replaceText(bodyChildren[i], search_display, search_link);
}

Better jQuery Embed Code validation (user input via textarea)

I'm working on a site where users can paste in embed codes from the likes of twitter, youtube, instagram, facebook, etc. The Embed code is validated and saved if valid.
The users can then see and edit the code and this is where some code fails validation. E.g. Twitter embed codes may contain < (aka '<') in the post name/text. When pasting in the code originally it passes validation as it contains <, but when displaying the code back to the user the browser shows < in the textarea and this is then submitted if the user clicks save. Our validation function treats this as the start of a tag and the validation fails.
Possible solution 1:
Better validation. The validation we use now looks like this It basically finds the tags (by looking for '<' etc) and checks that each open tag has a closing tag. There must be a better/standard/commonly used way:
(function($) {
$.validateEmbedCode = function(code) {
//validating
var input = code;
var tags = [];
$.each(input.split('\n'), function (i, line) {
$.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) {
var matches = tag.match(/<\/?([a-z0-9]+)/i);
if (matches) {
tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'});
}
});
});
if (tags.length == 0) {
return true;
}
var openTags = [];
var error = false;
var indent = 0;
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.closing) {
// This tag is a closing tag. Decide what to do accordingly.
var closingTag = tag;
if (isSelfClosingTag(closingTag.name)) {
continue;
}
if (openTags.length == 0) {
return false;
}
var openTag = openTags[openTags.length - 1];
if (closingTag.name != openTag.name) {
return false;
} else {
openTags.pop();
}
} else {
var openTag = tag;
if (isSelfClosingTag(openTag.name)) {
continue;
}
openTags.push(openTag);
}
}
if (openTags.length > 0) {
var openTag = openTags[openTags.length - 1];
return false;
}
return true
};
}
Possible solution 2:
Encode the text containing '<' (i.e. textLine.replace(/</g, '<')) without encoding tags like <blockquote class="...>.
I've been experimenting with something like:
$(widget.find("textarea[name='code']").val()).find('*')
.each(function(){
// validate $(this).text() here. Need to get text only line by
// line as some elements look like <p>some text <a ...>text
// </a>more text etc</p>
});
Possible solution 3:
Display < as < and not < in the browser/textarea. We use icanhaz for templating (much like moustache).
Using date.code = '<' with <textarea name="code">{{{code}}}</textarea> in the template does not work, neither does {{code}}.
So I played some more and the following works, but I am still interested in suggestions for better embed code validation or better answers.
After the edit form (inc textarea) code is created using the icanhaz template (i.e. after widget = ich.editEmbedWidgetTemplate(encoded_data);) I do the following to encode instances of < etc into < etc. ' has to be encoded manually using replace.
var embedCode = '';
$( widget.find("textarea[name='code']").val() )
.filter('*')
.each(function(){
embedCode += this.outerHTML.replace(/'/g, ''');
});
widget.find("textarea[name='code']").val(embedCode);

Fast filter in a list of records with JavaScript

I have a list with about 10 000 customers on a web page and need to be able to search within this list for matching input. It works with some delay and I'm looking for the ways how to improve performance. Here is simplified example of HTML and JavaScript I use:
<input id="filter" type="text" />
<input id="search" type="button" value="Search" />
<div id="customers">
<div class='customer-wrapper'>
<div class='customer-info'>
...
</div>
</div>
...
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#search").on("click", function() {
var filter = $("#filter").val().trim().toLowerCase();
FilterCustomers(filter);
});
});
function FilterCustomers(filter) {
if (filter == "") {
$(".customer-wrapper").show();
return;
}
$(".customer-info").each(function() {
if ($(this).html().toLowerCase().indexOf(filter) >= 0) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}
</script>
The problem is that when I click on Search button, there is a quite long delay until I get list with matched results. Are there some better ways to filter list?
1) DOM manipulation is usually slow, especially when you're appending new elements. Put all your html into a variable and append it, that results in one DOM operation and is much faster than do it for each element
function LoadCustomers() {
var count = 10000;
var customerHtml = "";
for (var i = 0; i < count; i++) {
var name = GetRandomName() + " " + GetRandomName();
customerHtml += "<div class='customer-info'>" + name + "</div>";
}
$("#customers").append(customerHtml);
}
2) jQuery.each() is slow, use for loop instead
function FilterCustomers(filter) {
var customers = $('.customer-info').get();
var length = customers.length;
var customer = null;
var i = 0;
var applyFilter = false;
if (filter.length > 0) {
applyFilter = true;
}
for (i; i < length; i++) {
customer = customers[i];
if (applyFilter && customer.innerHTML.toLowerCase().indexOf(filter) < 0) {
$(customer).addClass('hidden');
} else {
$(customer).removeClass('hidden');
}
}
}
Example: http://jsfiddle.net/29ubpjgk/
Thanks to all your answers and comments, I've come at least to solution with satisfied results of performance. I've cleaned up redundant wrappers and made grouped showing/hiding of elements in a list instead of doing separately for each element. Here is how filtering looks now:
function FilterCustomers(filter) {
if (filter == "") {
$(".customer-info").show();
} else {
$(".customer-info").hide();
$(".customer-info").removeClass("visible");
$(".customer-info").each(function() {
if ($(this).html().toLowerCase().indexOf(filter) >= 0) {
$(this).addClass("visible");
}
});
$(".customer-info.visible").show();
}
}
And an test example http://jsfiddle.net/vtds899r/
The problem is that you are iterating the records, and having 10000 it can be very slow, so my suggestion is to change slightly the structure, so you won't have to iterate:
Define all the css features of the list on customer-wrapper
class and make it the parent div of all the list elements.
When your ajax request add an element, create a variable containing the name replacing spaces for underscores, let's call it underscore_name.
Add the name to the list as:
var customerHtml = "<div id='"+underscore_name+'>" + name + "</div>";
Each element of the list will have an unique id that will be "almost" the same as the name, and all the elements of the list will be on the same level under customer-wrapper class.
For the search you can take the user input replace spaces for underscores and put in in a variable, for example searchable_id, and using Jquery:
$('#'+searchable_id).siblings().hide();
siblings will hide the other elements on the same level as searchable_id.
The only problem that it could have is if there is a case of two or more repeated names, because it will try to create two or more divs with the same id.
You can check a simple implementation on http://jsfiddle.net/mqpsppxm/
​

Removing content created by jquery

(according webshop)
I want to add an function remove, where I remove the whole entry inserted using ajax & jquery, but it is not working as I want to.
Using the following code:
$('#div').on('click', '.orderd', function() {
$(this).remove();
});
function UpdateTotal() {
ToAddHTML = '<h1>Shopping cart</h1>';
Totalprice = 0;
for (var i = 0; i < orders.length ; i++) {
var zoekresultaat = SubMenuItems.filter(function(v) {
return v.submenu_id === orders[i];
})[0];
Totalprice += parseFloat(searched.price);
ToAddHTML += '';
}
ToAddHTML += ''
$("#totalen").html(ToAddHTML);
}
This works, but when I console.log the array "orderd items", it still repeats the orderd items.
So when I click on a different item, the "just-deleted" order is popping up again.
It's kind of hard to explain my current problem, but I hope i've informed enough! For any questions, please ask! ill update my question!
You should remove the ordered id from your array, and recalculate your "basket" when an item is removed.
// =======================================================================
// ! Functie maken die de totalen-lijst bijwerkt
// =======================================================================
function WerkTotalenBij() {
ToeTeVoegenHTML = '<h1>Winkelmandje</h1>';
Totaalprijs = 0;
for (var i = 0; i < Bestellingen.length ; i++) {
var zoekresultaat = SubMenuItems.filter(function(v) {
return v.submenu_id === Bestellingen[i];
})[0];
Totaalprijs += parseFloat(zoekresultaat.price);
// here I put a "data-itemid" attribute to keep a raw reference to the item id
// this ID can be retrieved in the remove handler
ToeTeVoegenHTML += '<div class=besteld id=nummer'+Bestellingen[i]+' data-itemid="'+Bestellingen[i]+'">'+'€'+zoekresultaat.price+' '+zoekresultaat.title+'</br>(verwijder)</div><hr>';
}
ToeTeVoegenHTML += '<br/>Totale prijs per persoon :<br/> € '+Totaalprijs+'<br/>Minimaal 10 personen<br/> Aantal personen:<input type=text width="10px" /><input type="button" value="Ik ben klaar!">';
$("#totalen").html(ToeTeVoegenHTML);
}
$('#totalen').on('click', '.besteld', function() {
var itemID = $(this).data("itemid");
// remove the item ID from the array
var index = Bestellingen.indexOf(itemID);
if (index > -1) {
Bestellingen.splice(index, 1);
}
$(this).remove();
// recalculate orders
WerkTotalenBij();
});
But anyway, this is the typical work where you should rather use for example knockout.js libaray, where you can bind your DOM elements directly to your data, and it's enought to manipulate with your data, the GUI will automatically reflect to the changes. Believe me, it's worth to learn it, you won't regret.

Hiding a div element with javascript

Following is the code where I display matched user input in the div but I want to hide the div when there is no match for user input. I can't seem to do it with the following code:
HTML code:
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />
<div id="lc"> <p id='placeholder'> </p> </div>
JS code:
// JavaScript Document
s1= new String()
s2= new String()
var myArray = new Array();
myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
function test()
{
s1 = document.getElementById('filter').value;
var myRegex = new RegExp((s1),"ig");
arraysearch(myRegex);
}
function arraysearch(myRegex)
{
document.getElementById('placeholder').innerHTML="";
for(i=0; i<myArray.length; i++)
{
if (myArray[i].match(myRegex))
{
document.getElementById('lc').style.visibility='visible';
document.getElementById('placeholder').innerHTML += myArray[i] + "<br/>";
}
else
{
document.getElementById('lc').style.visibility='hidden';
}
}
}
Regular expressions are a powerful tool but using them for so trivial a job is often troublesome.First you are using a direct input as regular expression which is never so good.
I copied your code and analyzed the logic you are making many many errors
for(i=0; i<myArray.length; i++)
{
if (myArray[i].match(myRegex))
{
document.getElementById('lc').style.visibility='visible';
document.getElementById('placeholder').innerHTML += myArray[i] + "<br/>";
}
else
{
document.getElementById('lc').style.visibility='hidden';
}
consider your code above, if I enter football, it matches with football, and football is shown. Next it checks for baseball which does not match and visibility changes to hidden!!
Better logic
1.Check what strings match, and add them to the division.
2.Check how many strings have matched, if none, change visibility to hidden.
You are using regular expressions when this actully can be achieved easily with indexOf();
these are pure logical errors
consider using jquery. (with a little http://underscorejs.org/ for utility)
var myArray = ["Football", "Baseball", "Cricket","Hockey", "Basketball", "Shooting"]
$("#filter").keyup(function() {
if(_.include(myArray, $(this).val()) {
$('#lc').show()
} else {
$('#lc').hide()
}
}

Categories

Resources