logo
down
shadow

How can I access elements that have been created by forEach in Javascript?


How can I access elements that have been created by forEach in Javascript?

Content Index :

How can I access elements that have been created by forEach in Javascript?
Tag : javascript , By : Brian Drum
Date : November 28 2020, 12:01 PM

I wish did fix the issue. If you're gonna render htmlString don't concat variable in string literals:
"<div class='crappy way'>"+ variable +"</div>"
`<div class='better way'>${variable}</div>`
// A array to reference the root of SWAPI
const roots = ["Film", "People", "Planet", "Species", "Starship", "Vehicle"];

// A one time addition to DOM
const root = `
  <article class='${roots[4].toLowerCase()}s'>
    <header class='page'>
      <h2>${roots[4]}s</h2>
    </header>
  </article>`;

//Since an example of item wasn't provided, I guessed as to how it was structured. 
const items = [{
  name: "Death Star",
  model: "DS-1 Orbital Battle Station",
  films: ["https://swapi.co/api/films/1/"]
}, {
  name: "TIE Advanced x1",
  model: "Twin Ion Engine Advanced x1",
  films: ["https://swapi.co/api/films/1/"]
}, {
  name: "X-wing",
  model: "T-65 X-wing",
  films: ["https://swapi.co/api/films/2/", "https://swapi.co/api/films/3/", "https://swapi.co/api/films/1/"]
}];

// Reference main
const main = document.querySelector('main');

// Render htmlString root
main.insertAdjacentHTML('beforeend', root);

// Reference the new article tag 
const article = document.querySelector(`.${roots[4].toLowerCase()}s`);

//A Iterate through each object of the items array
//B Get the count of films array
//C1 if the count is more than 2...
//C2 .films should be rendered with an icon
//C3 else htmlString is without icon
//D htmlString for item
//E Render htmlStrings from C2-3 and D

for (let item of items) {//A
  let totalFilms = item.films.length;//B
  let films = totalFilms > 2 ? `<dd class='films'>Film Appearances: ${totalFilms} <i class='fas fa-medal'></i></dd>` : `<dd class='films'>Film Appearances: ${totalFilms}</dd>`;//C1-3

  let ship = `
    <dl class='item'>
      <dt class='name'>Starship Name: ${item.name}</dt>
      <dd class='model'>Starship Model: ${item.model}</dd>
      ${films}
    </dl>
    <hr>`;//D
  article.insertAdjacentHTML('beforeend', ship);//E
}
:root {font: 400 3vw/1.5 'Nova Square'}
dt, dd {
  margin-inline-start: 0px;
  margin-bottom: 4px;
}
<link href="https://fonts.googleapis.com/css?family=Nova+Square&display=swap" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.9.0/css/all.css" rel="stylesheet" crossorigin="anonymous">

<header class='site'>
  <h1>Star Wars</h1>
</header>
<main></main>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Can't access Elements previously created by innerHTML with Javascript/Prototype


Tag : javascript , By : Pavel K.
Date : March 29 2020, 07:55 AM
will be helpful for those in need So $('akas-admin') returns null but document.getElementById("akas-admin") does not. The $ function is mostly just a wrapper for document.getElementById so it's unusual for this to break down. Have you tried using Element.extend(document.getElementById('akas-admin'))?
Do you have any other libraries loaded? Can you recreate the problem in jsFiddle?

access elements created by JavaScript at runtime (document.write)


Tag : javascript , By : Eric
Date : March 29 2020, 07:55 AM
I hope this helps you . The simplest solution to get JavaScript support is use a UIWebView. It doesn't need to be added to the view hierarchy.
UIWebView *webView = [[UIWebView alloc] init];
NSString *url = @"http://www.google.com";
webView.delegate = self;
frames = 0; // NSUInteger instance variable to track frame loads
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];    
- (void)webViewDidStartLoad:(UIWebView *)webView {
    frames++;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    frames--;
    if (frames > 0) return;

    NSString *document = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];

    // Use HPPLE to parse
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    // Handle error
}

Undefined value on id with jQuery on elements created inside Knockout foreach


Tag : jquery , By : Brian
Date : March 29 2020, 07:55 AM
hope this fix your issue Don't mix Knockout and jQuery in that way. Instead, avoid using jQuery for logic, and try not to use information from the DOM inside your view models.
If you need to make sub-viewmodels aware of their parent attributes, there are multiple ways to do this. For example you could use Knockout contexts on click events:
function CommentReply(data) {
  var self = this;
}

function Comment(data){
  var self = this;
  self.txt = ko.observable();
  self.isEditing = ko.observable(!data || !data.id);
}

function Ad(data) {
  var self = this;
  self.txt = ko.observable(data.txt);
  self.comments = ko.observableArray([]);
  
  self.addComment = function() {
    self.comments.push(new Comment());
  }
  
  self.saveComment = function(comment) {
    console.log(self); // id accessible here
    console.log(comment); // id accessible here
    comment.isEditing(false);
  }
}

function ViewModel() {
  var self = this;  
  self.ads = ko.observableArray([]);
  
  self.loadAds = function() {
    // Normally loading with Ajax, but stubbing it here:
    self.ads.push(new Ad({ id: 1, txt: "Buy shampoo now!" }));
    self.ads.push(new Ad({ id: 2, txt: "Best pizza in town.!" }));
  }
  
  self.loadAds();
}

$(function() {
  ko.applyBindings(new ViewModel());
});
.ad { padding: 10px; margin: 5px; border: 1px solid gray; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="foreach: ads">
  <div class="ad">
    <div data-bind="text: txt"></div> 
    <input type="button" data-bind="click: addComment" value="add comment" />
    <div data-bind="foreach: comments">
      <p data-bind="text: txt, visible: !isEditing()"></p>
      <div data-bind="visible: isEditing">
        <textarea data-bind="value: txt"></textarea>
        <input type="button" data-bind="click: $parent.saveComment" value="save comment">
    </div>
  </div>
</div>

How to fadeIn and fadeOut individual Div elements created with foreach?


Tag : javascript , By : Boyer C.
Date : March 29 2020, 07:55 AM
wish helps you You should not use same id for multiple elements. Id for each element should always be unique. If you use same id the selector returns only the first element with matching id. You should use class with same name.
For each element clicked you can find its parent and for that you can find a child with required class and toggle its visibility.
  function showItems(ev) {
    var x = $(ev.target).parents('.row.rounded-top').find('.showItemDiv');
    $(x).toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row rounded-top" style="margin-top:5px;background-color:lightblue;padding:5px;" onclick="showItems(event)">
  <div class="col-lg-6 col-md-12 col-sm-12 col-xs-12">
    <div class="row">
      <span class="" style="font-size:10px;">Item Name:</span>
    </div>
    <div class="row">
      <p>
        <span class="" id="">Item 1</span>
      </p>
    </div>
  </div>

  <div class="showItemDiv" style="display: none;">
    <div class="row" style="margin-top:15px;background-color: #FFE4E1;padding:5px;">
      <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">

        <div class="row">
          <span class="" style="font-size:10px;">Time Setup:</span>
        </div>

        <div class="row">
          <p>
            <span class="" id="id">1</span>
          </p>
        </div>

      </div>
    </div>
  </div>
</div>

<div class="row rounded-top" style="margin-top:5px;background-color:lightblue;padding:5px;" onclick="showItems(event)">
  <div class="col-lg-6 col-md-12 col-sm-12 col-xs-12">
    <div class="row">
      <span class="" style="font-size:10px;">Item Name:</span>
    </div>
    <div class="row">
      <p>
        <span class="" id="">Item 2</span>
      </p>
    </div>
  </div>

  <div class="showItemDiv" style="display: none;">
    <div class="row" style="margin-top:15px;background-color: #FFE4E1;padding:5px;">
      <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">

        <div class="row">
          <span class="" style="font-size:10px;">Time Setup:</span>
        </div>

        <div class="row">
          <p>
            <span class="" id="id">2</span>
          </p>
        </div>

      </div>
    </div>
  </div>
</div>

Javascript - Can not access array elements of an array created from a csv file


Tag : javascript , By : brennen
Date : March 29 2020, 07:55 AM
I wish this helpful for you Probably neither the fastest, nor the most efficient solution, but here is what you can do to get the desired format, splitted in various steps:
Make a set of unique keys, so that you will be aware of what keys you will need to use. Map the above keys and get, from the original array, all the values for that key.
var parsedArray = [
    { "HeaderA": "A1", "HeaderB": "B1", "HeaderC": "C1" },
    { "HeaderA": "A2", "HeaderB": "B2", "HeaderC": "C2" },
    { "HeaderA": "A3", "HeaderB": "B3", "HeaderC": "C3" }
];
const uniqueKeys = [...new Set(...parsedArray.map(i => Object.keys(i)))];

const res = uniqueKeys.map(k => {
    return [k, ...parsedArray.map(i => i[k]).filter(i => i !== null && i !== undefined)];
});
console.log(res);
[...new Set(...parsedArray.map(i => Object.keys(i)))];
var myArray= []

d3.csv("data.csv", function(data){
    myArray.push(data)
    console.log(myArray)
    // Write your code here, NOT OUTSIDE OF THIS FUNCTION BLOCK.
});
Related Posts Related QUESTIONS :
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Make web service not accessible by browser?
  • Select DOM elements within template
  • How to customize angular ui-grid row background color?
  • Binding data in two respective $scope in AngularJS, how?
  • react put some props after import class
  • Variable is distributed among same components
  • switch class in jQuery/JavaScript for active/inactive state
  • How To Track Outbound Clicks Using Javascript
  • How to get total seconds elapsed since the beginning of the month?
  • Protractor: Stale element reference at "browser.wait(EC.visibilityOf(confDial), FIFTY_SECONDS);"
  • Access to an array inside an object
  • Reseting an JavaScript Interval with different value?
  • Learning Angular for the first time - version 2 or 4?
  • Rendering RSS feed (XML) in React with jquery, why do object values parsed from the feed seem empty?
  • Node.js xml2js http.request tag matching
  • applying texture to custom plane geometry in Threejs
  • How do I pass an Event as a function parameter in HTML written inside JavaScript variable?
  • Interface of object parameter with default value and default property
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com