I have this array in javascript:
[div.parts, div.editor, div.inside-1, div.container-2, div.inside-wrapper, div#content, div.whitebgpan, div, div#maindiv, body, html]
How can I convert it into string, so that the output will be:
div.parts div.editor div.inside-1 div.container-2 div.inside-wrapper div#content div.whitebgpan div div#maindiv body html
here is my code:
jQuery(document).on('click', function(e){
var ClickedParents = jQuery(e.target).parents(); //Get all parents of clicked element
var ClickedParents_array = jQuery.makeArray(ClickedParents); //Make array
console.log(ClickedParents_array); //Show output in colsole
});
You can use a combination of the jQuery each function and JavaScript's Array.Join function to solve this problem.
DEMO: http://jsfiddle.net/zay015ex/1/
I've artificially retrieved an array of jQuery objects to show how you can solve this, but the concept is common to your problem.
HTML
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
JavaScript
var arrayOfObjects = $('#parent').children();
var ids = [];
$.each(arrayOfObjects, function(i, val)
{
ids.push(val.id);
});
var idString = ids.join(' ');
You can read up more on the jQuery each function here.
You can read up more on the JavaScript's Array.Join function
here.
===== Update =====
Ok, the following code is tested, just open a console and paste this. it selects all div tags and convert into selector string.
$.map($('div'),function toSelector(elem){
var jqObj = $(elem)
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
})
===================
Supposing they're jquery objects, you have to build the string manually.
For example, do something like following. (not tested)
function toSelector(jqObj){
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
}
array.map(toSelector)
I think below code is helpful for you.
<script type="text/javascript">
String.prototype.replaceAll = function ( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
try{
var arr = [];
arr.push('div.parts', 'div.editor', 'div.inside-1', 'div.container-2', 'div.inside-wrapper', 'div#content', 'div.whitebgpan', 'div', 'div#maindiv', 'body', 'html');
var stringData = arr.toString();
stringData = stringData.replaceAll(",", " ");
console.log(stringData);
}catch(e){
alert(e)
}
</script>
Related
i'm facing problem to construct html list.
i'm expecting same result as shown by (Expected output(Static) Below:)
Question: comm_id having same value should be constructed 1 time
here is what i'm trying
var list = [
{'com_id':12,'text':'Apple'},
{'com_id':12,'text':'Banana'},
{'com_id':91,'text':'cake'},
{'com_id':91,'text':'cup cake'},
];
var dataMap = {}, str = '';
for(var i = 0; i < list.length; i++){
if(!dataMap[list[i]['com_id']]) {
dataMap[list[i]['com_id']] = list[i];
str += '<li>com_id:'+list[i]['com_id']+' <span>'+list[i]['text']+'</span><span>'+list[i]['text']+'</span></li>';
}
}
$('#dynamic_const').html(str);
span{
display:inline-block;
padding:10px;
margin:2px;
background:#eee;
border-radius:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamic_const">
</div>
<p>Expected output(Static) Below:</p>
<div id="static">
<ul>
<li>com_id:12 <span>Apple</span><span>Banana</span></li>
<li>com_id:91 <span>cake</span><span>cup cake</span></li>
</ul>
</div>
Please help me thanks in advance!!!
var list = [
{'com_id':12,'text':'Apple'},
{'com_id':12,'text':'Banana'},
{'com_id':91,'text':'cake'},
{'com_id':91,'text':'cup cake'}
];
// group the text for each com_id
var reducedList = list.reduce( ( elements, element ) => {
if ( !elements[ element.com_id ] ) {
elements[ element.com_id ] = { com_id: element.com_id, text: [] }
}
elements[ element.com_id ].text.push( element.text );
return elements;
}, {} );
console.log( reducedList );
// build the html
var newHTML = Object.values( reducedList ).map( element => {
return `<li>com_id:${ element.com_id }<span>${ element.text.join( '</span><span>' ) }</span></li>`;
} );
console.log( newHTML );
If you just want to build your HTML you can use Jquery $.each
var html = '';
$.each(list, function(i, el){
html += '<li>com_id:' + el.com_id + ' <span>' + el.text + '</span></li>';
});
$('#dynamic_const').html(html);
here's a function that checks if there's a link in text (if so, replaces it with a clickable one)
example:
The actual resolution of this image is 3067x2276, not 4381x3251. See this page for information on how to find out what the resolution of an image is.
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
if (matches.length > 2) {
var replace = `${matches[1]}`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} else {
$("#text").append('<p>hello</p>');
}
});
}
<body>
<div class="container">
<div id="art" class="img column1">
</div>
<div id="text" class="comment column2">
</div>
</div>
</body>
I tried running it on chrome's javascript console, replacing $("#text").append... with console.log("hello"), and it works. Why does it not work on jsfiddle?
use try and catch instead
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
try {
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
var replace = `${matches[1]}`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} catch(err) {
$("#text").append('<p>' + rawComment + '</p>');
}
});
}
exec returns null if regex not matched result. Just check it at first.
...
if (matches && matches.length > 2) {
...
I have upload my JavaScript code :
$(document).ready(function(){
$("#remain_credit").click("calculate_remain_credit");
});
function calculate_remain_credit() {
var hour_start = document.getElementById(parseInt('credit_taken'));
var hour_end = document.getElementById(parseInt('course_credit'));
var hour_total = credit_taken - course_credit;
document.getElementById('remain_credit').innerHTML = remain_credit;
}
And I am uploading also my Laravel form here:
<div class="form-group">
{{Form::label('credit',' Remain Credit ')}}
{!! Form::number('remain_credit', null, array('id'=>'remain_credit','placeholder' => ' Remain Credit ','class' => 'form-control')) !!}
</div>
How can I fix this problem?
You should fix three problems in your code :
The click event attachment should look like :
$("#remain_credit").click(calculate_remain_credit);
Removing the quotes :
$("#remain_credit").click("calculate_remain_credit");
__________________________^_______________________^
You need to replace innerHTML by value if you want to update the input value, should be :
document.getElementById('remain_credit').value = remain_credit;
You've to parse after getting the value so :
var hour_start = document.getElementById(parseInt('credit_taken'));
var hour_end = document.getElementById(parseInt('course_credit'));
Should be instead like :
var hour_start = parseInt( document.getElementById('credit_taken').value );
var hour_end = parseInt( document.getElementById('course_credit').value );
The full updated code will be :
$(document).ready(function(){
$("#remain_credit").click(calculate_remain_credit);
});
function calculate_remain_credit() {
var hour_start = parseInt( document.getElementById('credit_taken').value );
var hour_end = parseInt( document.getElementById('course_credit').value );
var hour_total = credit_taken - course_credit;
document.getElementById('remain_credit').value = remain_credit;
}
parseInt should be first and then document.getElementById:
$("#remain_credit").click(calculate_remain_credit);
function calculate_remain_credit() {
// here use parseInt before getElementById
var hour_start = parseInt(document.getElementById('credit_taken').value);
var hour_end = parseInt(document.getElementById('course_credit').value);
var hour_total = credit_taken - course_credit;
document.getElementById('remain_credit').value = hour_total;
}
Suppose you have an HTML page that contains sections in different languages, like this:
<html lang=en>
<div lang="th">
<p id="test1">ไทย</p>
</div>
<p id="test2">Implicitly English</p>
<div lang="en-CA">
<p id="test3">As Canadian as possible under the circumstances</p>
</div>
<p lang="en-AU"id="test4">Explictly Aussie</p>
</html>
Is there a direct way to discover which particular language code applies to a given HTML element? Something like:
// pseudo-code
var lang = myElement.getLang()
Here's what appears to be a very roundabout solution:
function getLang(element) {
var lang = element.getAttribute("lang")
if (!lang) {
var elements
, languages
, language
, ii
, selector
// Find all elements with an explicit lang attribute
elements = [].slice.call(document.querySelectorAll("*[lang]"))
// Determine which languages are present
languages = []
for (ii in elements) {
lang = elements[ii].getAttribute("lang")
if (languages.indexOf(lang) < 0) {
languages.push(lang)
}
}
lang = "" // reset
for (ii in languages) {
language = languages[ii]
selector = ":lang(" + language + ")"
elements = [].slice.call(document.querySelectorAll(selector))
if (elements.indexOf(element) > -1) {
if (lang.length < language.length) {
lang = language
}
}
}
}
return lang
}
Is there a more obvious way?
jsFiddle
I updated your fiddle with the following code, which you can run in this snippet. This simplifies it greatly.
function getLang(elem) {
var lang = "";
if (elem) {
var elements = [];
var queryResult = document.querySelectorAll("[lang]");
try {
//Wrapping in a try catch block to handle unsupported browsers.
elements = [].slice.call(queryResult);
} catch (error) {
for (var i = 0, len = queryResult.length; i < len; i++) {
elements.push(queryResult[i]);
}
}
if (elements.length > 0) {
//Find in the NodeList where the element is either itself or the first parent with lang attribute of the given element.
var matches = elements.filter(function(e) {
return e === elem || e.contains(elem);
}); //ES2015 -> elements.filter(e => e === elem || e.contains(elem));
var match = matches.length > 0 ? matches[matches.length - 1] : matches[0];
lang = match.lang ? match.lang : lang;
}
}
return lang;
}
var result = getLang(document.querySelector("#test1")) + " ";
result += getLang(document.querySelector("#test2")) + " ";
result += getLang(document.querySelector("#test3")) + " ";
result += getLang(document.querySelector("#test4"));
alert(result);
<body lang=en>
<div lang="th">
<p id="test1">ไทย</p>
</div>
<p id="test2">Implicitly English</p>
<div lang="en-CA">
<p id="test3">As Canadian as possible under the circumstances</p>
</div>
<p lang="en-AU" id="test4">Explictly Aussie</p>
</body>
<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div>cout<<"hey";cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
I wanted to find cout using regex, something like /cout[^;]*;/ and then wrap it with a span.
<div id="wrapper">
<div>if(true)<span class="openParen bm1">{</span></div>
<div><span id="group">cout<<"hey";</span>cin>>x;</div>
<div><span class="closeParen bm1>}</span></div>
</div>
How will i find the regex occurence and the wrap it with a span? Anyone please?
UPDATE: I inserted cin>>x; after cout, cin shouldn't be wrapped.
I want to use something like this
text.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>');
But i dont know how to apply it in DOM. anyone?
BUG for cin>> and cout<<, they cant be wrap until ; http://jsfiddle.net/3N4AE/11/
This is how you would apply the regex to your DOM using jQuery:
$('#wrapper div').filter(':contains("cout")').each(function () {
$(this).html($(this).text().replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
Demo fiddle
update Regex way
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.html(txt.replace(/(cout[^;]*;)/g, '<span class="group">$1</span>'));
});
DEMO
var x =$('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('').append('<span id="group">'+txt+'</span>');
updated after OP updated question
DEMO
var x = $('#wrapper div').filter(':contains("cout")');
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
update
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else {
x.append(val + ';');
}
});
});
updated after koala-dev comment
DEMO
$('#wrapper div').filter(':contains("cout")').each(function () {
var x = $(this);
var txt = x.text();
x.text('');
var cout = txt.split(';');
$.each(cout, function (i, val) {
if (val.indexOf('cout') > -1) {
x.append('<span class="group">' + val + ';</span>');
} else if ($.trim(val) != '') {
x.append(val + ';');
}
});
});
This should help
var pattern = /cout[^;]*;/;
var txt = $('#wrapper').find('div:nth-child(2)').text();
var el = $('#wrapper').find('div:nth-child(2)');
$(el).text("").append('<span id="group">' + txt + '</span');
jsfiddle