Hide the div elements if not including specific keywords - javascript

I have seen a brunch of solution about how to show/hide the div which do not contains(or contains) specific keywords but none of them do help.
So far I have done some codes like this:
<div class="media">Title : orange</div>
<div class="media">this is something about orangessss yolo</div>
<div class="media">Title : apple</div>
<div class="media">this is something about apple yolo</div>
<button id="filter">test</button>
And I have a method to fliter the elements:
var KeywordArr = ["orange","orangessss"];
$('#filter').click(function () {
var key = $(".media");
var word= key.find(".media").html();
if(!word && word.toLowerCase().match([KeywordArr])) {
$(".media").css("display", "none");
}
});
These codes suppose to add "display:none" to every "media" class which does not contains any keywords included in the array. But it's not working as my exception.
So how can I hide all the elements when the "< div"> do not have the value contain in keywordArr?
Solution:
$('#filter').click(function () {
var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();
for (var i = 0; i < KeywordArr.length; i++) {
res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}
elems.not(res).hide();
});

Try to use :contains() selector at this context,
var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();
for (var i = 0; i < KeywordArr.length; i++) {
res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}
elems.not(res).hide();
Also note that contains selector is case sensitive.
DEMO

To keep your code more declarative you can use array foreach. also make sure to keep you variable names all lowercase.
var elems = $(".media");
var keywordArr = ["orange", "orangessss"];
var res = $();
keywordArr.forEach(function(keyword){
res = res.add(elems.filter(":contains('" + keyword + "')"));
});
elems.not(res).hide();
Also if you can write the Same code with ES6 Template literals, here is a link to Demo
const elems = $(".media");
const keywordArr = ["orange", "orangessss"];
let res = $();
keywordArr.forEach(
(keyword) => res = res.add(elems.filter(`:contains(${keyword})`))
);
elems.not(res).hide();

Related

Accessing property's array with a specific id

What i wanted to do is access random property for example let1, let2 with their first string in array which is ID "1" , "2" , "3" , "4" , "5".
brojleta is actually that ID i mentioned before, it is different from id down there(var id = item[0][1]). What i need is to get all other strings based on their ID. I tried it like this :
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
var location = decodeURI(window.location.toString());
var index = location.indexOf("?") + 1;
var subs = location.substring(index, location.length);
var splitted = subs.split("&");
for (i = 0; i < splitted.length; i++) {
var s = splitted[i].split("=");
var pName = s[0];
var pValue = s[1];
if (pName == brojleta) {
return pValue;
}
}
}
var brojleta = getParamValue("id");
var item = data.find(item => item[0][0] === brojleta);
var id = item[0][1]
var datumpolaska = item[0][2]
var datumdolaska = item[0][3]
var polazniaerodrom = item[0][4]
var dolazniaerodrom = item[0][5]
var brojsedista = item[0][6]
var cenakarte = item[0][7]
var data1 = data.let1[0];
var data2 = data.let2[0];
var data3 = data.let3[0];
var data4 = data.let4[0];
var data5 = data.let5[0];
/* this is the code for adding data from array to table */
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
var row3cells = $("#row3 td");
var row4cells = $("#row4 td");
var row5cells = $("#row5 td");
for (var index=0; index<8; index++) {
$(row1cells[index]).html(data1[index]);
$(row2cells[index]).html(data2[index]);
$(row3cells[index]).html(data3[index]);
$(row4cells[index]).html(data4[index]);
$(row5cells[index]).html(data5[index]);
}
});
To make your code work you should choose variable data to be an array of arrays instead of an object. Then you can run var item = data.find(item => item[0] === brojleta); and similar operations.
It would look like this:
var data = [["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"],
["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"],
["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"],
["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"],
["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]];
I think you really want this:
Remove the || 3 // test #3 after testing
Try removing the 3 from the input and click search too
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
return new URLSearchParams(document.location.search.substring(1)).get(brojleta)
}
function show(item) {
$tr = $("<tr/>"), $tbd = $("#tbd");
$.each(item,function(_,fld) {
$tr.append("<td>"+fld+"</td>");
})
$tr.appendTo($tbd);
}
function showAll() {
Object.keys(data).forEach(function(key) {
show(data[key][0]);
})
}
$(function() {
$("#search").on("click",function() {
$("#tbd").empty();
var brojleta = $("#broj_leta").val();
if (brojleta) show(data["let"+brojleta][0])
else showAll();
});
var brojleta = getParamValue("id") || 3 // test #3
if (brojleta) $("#broj_leta").val(brojleta);
$("#search").trigger("click");
})
th, td { border:1px solid lightgrey; padding: 3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="broj_leta" /><button id="search">Search</button>
<table>
<thead>
<tr>
<th>id</th>
<th>Datumpolaska</th>
<th>Datumdolaska</th>
<th>Plazniaerodrom</th>
<th>Dolazniaerodrom</th>
<th>Brojsedista</th>
<th>Cenakarte</th>
</tr>
</thead>
<tbody id="tbd">
</tbody>
</table>
You can first filter the data based on ID and then map your required variable to final output array in below code output.
var brojleta = 1;
const mappedarray = Object.entries(data).filter((k,v)=>{return k[0] == "let"+brojleta});
console.log(mappedarray[0][1][0]);
You can use the lodash function find().
This is the same function as Array.find but it works on Object.
https://lodash.com/docs/4.17.11#find

JS - combining array items together in one item

For example I want to collect some tags (lets say paragraph):
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length
I loop through (iterate):
for (var i = 0; i < tagsCollectionLength; i++)
{
//get an array:
var tagsCollectionArray = tagsCollection[i];
}
Now what to do to get all array items as ONE item:
so it won't looks like:
[paragraph1, paragraph2, paragraph3]
but like:
[paragraph1paragraph2paragraph3]
I did try join. concat. etc. without success probably I'm doing something wrong, any help is appreciated. Thanks.
you can keep a variable outside the for, append the strings inside for and when for finishes, push it inside an array.
Here's how to do that -
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length;
var tags = "", tagsCollectionArray = [];
for (var i = 0; i < tagsCollectionLength; i++)
{
tags = tags + tagsCollection[i];
}
tagsCollectionArray.push(tags);
Suppose you have this html
<div>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>
</div>
Assuming the result you want is an Array of all the paragraphs's content ([paragraph1paragraph2paragraph3]), then you could do the following:
tagsCollection = document.getElementsByTagName('p');
var ar = [];
for(var i = 0; i < tagsCollection.length; i++ ) {
ar.push(tagsCollection[i].innerText)
}
console.log([ar.join('')]) // => ["abcde"]
See this fiddle
As I have already commented, you can use Array.join("").
JSFiddle.
(function() {
var data = [];
var str = [].map.call(document.getElementsByTagName('p'), function(item) {
return item.innerHTML;
}).join("");
data.push(str);
document.write("<pre>" + JSON.stringify(data) + "</pre>");
})()
<p>hello</p>
<p>workd</p>
<p>test</p>

mapping Json data and adding data attr

I have a difficulty with mapping my my Json data. I would like to add data attr to each div with .name class. So as the result is like that:
<div class="name" data-key="sth"> sty</div>
Key can be got like that: ['streme'].key
here is my buggy JS:
function getExistingLinks() {
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link'].key
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
// $('div').each( function(index) {
$('div')[index].data("key") = keys[index];
}
container.appendChild(div);
});
});
return false;
}
names.forEach(function(name,index) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key") = keys[index];
});
You need to remove the quotes in the $() selector!
As per your comment, may be try doing like:
var i = 0;
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
$('div').data("key", keys[i]);
container.appendChild(div);
i++;
});
the preferred method is to only add to the DOM once, as adding to the DOM will cause a redraw on each.
psuedo code as not sure what name represents in your innerHTML:
var divs = [];
for (var i, len = names.length; i < len; i++) {
divs.push($(''+name+'').data("key", keys[i]));
}
$container.append(divs);
http://codepen.io/jsdev/pen/2866265243563efd79cf05a5b12202b3
try something like this
$('.name').data('key') //will give you sth

jQuery convert data-* attributes to lower camel case properties

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
if (data['class-name']) {
options.className = data['class-name'];
}
if (data['align-x']) {
options.alignX = data['align-x'];
}
if (data['align-y']) {
options.alignY = data['align-y'];
}
if (data['offset-y']) {
options.offsetY = data['offset-y'];
}
if (data['offset-x']) {
options.offsetX = data['offset-x'];
}
$this.poshytip(options);
});
I would use a for..in loop to read the data-* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... Source code reference.
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[keys] = data[keys];
}
// For older versions of jQuery you can use $.camelCase function
for (var keys in data) {
options[$.camelCase(keys)] = data[keys];
}
});
DEMO
for jQuery 1.4.4,
$('.poshytip-trigger').each(function(index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[camelCase(keys)] = data[keys];
}
});
//copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase
function camelCase(str) {
return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) {
return (letter + "").toUpperCase();
});
}
DEMO for 1.4.4
Something like this - It does convert offset-x to offsetX:
http://jsfiddle.net/8C4rZ/1/
HTML:
<p data-test="sdsd" data-test2="4434"></p>​
JavaScript:
$(document).ready(function() {
var options = {};
for (var key in $("p").data()) {
options[key] = $("p").data(key);
}
console.log(options);
});​
But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take all data- attributes.
var names = ["className", "alignY", ...];
$(names).each(function(ind, name){
var dataName = name.replace(/[A-Z]/, function(letter){
return letter.toLowerCase();
});
if(data[dataName]){
options[name] = data[dataName];
}
});
Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.
Try using a for in loop.
var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x'];
for (x in array) {
if(data[array[x]]) {
options[array[x]] = data[array[x]];
}
}
Update: In response to the OP's clarification, he could write something like this:
var Pair = function(hyphenated, camcelCased) {
this.hyphenated = hyphenated;
this.camelCased = camelCased;
}
var array = [
new Pair('class-name', 'ClassName'),
new Pair('align-x', 'alignX'),
new Pair('align-y', 'alignY'),
new Pair('offset-x', 'offsetX'),
new Pair('offset-y', 'offsetY')];
var i, optionNameHyphenated, optionNameCamelCased;
for(i = 0; i < array.length; i++) {
optionNameHyphenated = array[i]['hyphenated'];
optionNameCamelCased = array[i]['camelCased'];
if (data[optionNameHyphenated]);
options[optionNameCamelCased] = data[optionNameHyphenated];
}

getElementByName & Regex

How do I loop through all elements using regular expression in getElementByName?
If you mean like:
var elementArray = document.getElementsByName("/regexhere/");
then no that would not be possible.
To do what you want to do you would have to get all the elements, then go through each one and check the name of it.
Heres a function that will go through all the elements and add all the elements with a certain name to an array:
function findElements(name)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].name) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elName = "customcontrol";
var elArray = customcontrol(elName);
Or it might be easier by className
function findElements(className)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elClassName = "classname";
var elArray;
if (!document.getElementsByClassName)
{
elArray= findElements(elClassName );
}
else
{
elArray = document.getElementsByClassName(elClassName);
}
This would do what you want, without the need for getElementByName.
Although I think you meant getElementsByName
If you wanted to look for an element with only the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
If you wanted to look for an element with that STARTED with the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name);
EDIT:
If your using jQuery, which would be easier, then this would do:
var elArray = $("*[name^='customcontrol']");
//Use JavaScript to loop through
for (var a = 0; a< elArray.length;a++)
{
//Loop through each element
alert(elArray[a]);
}
//Or
$("*[name^='customcontrol']").css("color","red"); //Or whatever you want to do to the elements
Use a custom selector in jQuery. You probably want an example with parameters.

Categories

Resources